Copyright: Copyright ©1996-97, Acadia Software, Inc.


About Acadia Infuse

Acadia Infuse enables you to rapidly create JavaScript scripts and develop LiveWire applications within a visual, drag-and-drop editing environment. By using visual trees to display JavaScript objects and other language elements, Acadia Infuse makes it easy to learn JavaScript and maximize productivity. Its integrated Script Navigator allows you to visually navigate your HTML or LiveWire source file. Plus, if you develop with LiveWire, you can access Site Manager and the command-line compiler directly from within the editor itself.


About Acadia Software

Acadia Software, Inc. develops and markets Acadia Infuse, the first editor for the JavaScript programming language. Founded in 1995, Acadia Software, Inc. is a privately-held company headquartered in the greater Boston, Massachusetts area. Acadia is committed to providing its customers with Web software products and solutions. The company draws from the years of software consulting and software development experience of its founders to deliver tools for Web site developers. Acadia Software is a Netscape ONE licensee, supporting JavaScript development as a part of its support for the Netscape ONE platform.

Contact Information

Acadia Software

1300 Massachusetts Avenue

Suite 220

Boxborough, MA 01719 USA

Phone 508/264-4881

Fax 508/635-9211

URL http://www.acadians.com

Email info@acadians.com

Support support@acadians.com


Object Tree

Click the left mouse and drag the object, method, or property definition into your source file. Or, hold the Ctrl key while dragging to instantiate the selected object in your code.


HTML Tree

Click the left mouse and drag the HTML tag into your source file.


Script Navigator

The Script Navigator gives you a visual look at your source file and allows you to quickly jump to a function or object by double-clicking on the item.


Enter the name of your custom object in this field.


An object may contain properties or methods. Select the appropriate radio button and enter the name of the element in the blank field. Press Add to include this element in your custom object definition.


Shows the list of properties and methods of the custom object.


Frequent Scripts

You can quickly drop in frequently used JavaScript and LiveWire code into your source file by using the Frequent Scripts feature. Select the script of your choice from the dialog box and click OK to paste the code into the current insertion point in the editing window.

Hint: Double-clicking the script selection in the list will automatically click the OK button for you.


Lists the available browers you can use to preview your source files. Acadia Infuse will automatically look for a version of Netscape Navigator and Microsoft Internet Explorer on your system. If found, they will be added to the list. You can also add additional browsers to your list by clicking the Add button.


Click Add to add a new preview browser. If you have a single copy of Netscape Navigator or Microsoft Internet Explorer on your system, you will not need to use this button to add these browsers to your list (as this is done for you automatically). However, if you wish to add another type of browser or if you have multiple versions of Netscape Navigator or Microsoft Internet Explorer, you can add these to your preview browser list.


Click Edit to edit the current properties of the selected browser.


Click the Delete button to remove the selected browser from the list.

Note: Acadia Infuse looks at your system configuration to determine the current Netscape Navigator and Microsoft Internet Explorer browsers. Therefore, since these settings always reflect what is installed on your system, you cannot delete these browsers from the preview list unless your actually remove the browsers from your system.


Select the default window size for the preview window.

Note: This option is only available for the current Netscape Navigator and Microsoft Internet Explorer browsers, not additional browsers you add.


Click the Choose Font button to select the default font and size.


Editor Options

There are several options available for the Acadia Infuse editor.

Auto Indent - Check this option to automatically position the cursor under the first nonblank character of the preceding nonblank line when you press the Enter key.

Insert Mode - Check this option to inserts text at the cursor without overwriting existing text. If unchecked, text at the cursor is overwritten.

Typing Replaces Selection - Check this option to automatically replace selected text as you type.

Use Syntax Highlighting - Check this option to perform syntax highlighting. Use the Colors tab of the Preferences dialog box to set color syntax settings.

Undo Limit - Enter the number of undos you wish to set.

Vertical Spacing - Select the amount of vertical spacing (space between lines) you wish to set to the editor. Default is None.

Tab Stop Size - Enter the number of character columns you wish the cursor to move each time you press Tab.


Editor Colors

Use the Colors tab to set the colors used in editor windows. The colors in the Language group are only active if the Use Syntax Highlighting option is checked on the Editor tab of the Preferences dialog box.


Enter the directory you wish to use as the default path when you start Acadia Infuse.


Select the type of description you wish to view in the Frequent Scripts dialog box. Descriptive View typically shows a description of the code snippet in sentence style, while Code View depicts the code fragment using its function name (as applicable).


You can use color syntax highlighting to focus either on the JavaScript code or the HTML tags. Default is JavaScript code. This option only is activated if the Use Syntax Highlighting option is checked on the Editor tab of the Preferences dialog box.


Select the desired editor popup menu you wish to work with. The popup menu is activated when you click the right button of your mouse when in an editor window. The available options are shown below.

Editor Standard	Scripter Alternative

Cut	Cut

Copy 	Copy

Paste	Paste

Select All	Preview

Find 	Find Matching Brace

Insert Frequent Script 	Set Bookmark

Add Frequent Script	Find Bookmark

Insert Frequent Script

Add Frequent Script


Enter the full path and file name for LiveWire Site Manager.


Enter the full path and file name for the LiveWire command-line compiler.


Tools | Preview
Preview

Select the browser you wish to use to preview the active source file and click OK. To add or edit browser list, refer to the Preview List on the Preview tab of the Preferences dialog box.


Click the Add button to add a new code snippet to the Frequent Scripts library.


Select the Tree to which you wish to add the code snippet.


Select the Object to which you wish to add the code snippet. For example, if your code is most closely associated with a form object, select Form from the list.


Enter the name you wish to give the selected code. This text is displayed when using the Code View option on the General tab of the Preferences dialog box.

Tip: If the snippet is a function, you will usually want to enter the function name in this box.


Enter a fuller description you wish to use to characterize the code snippet. This text is displayed when using the Descriptive View option on the General tab of the Preferences dialog box.


This window shows the code you selected. Modify as desired before clicking the OK button.


Top 10 Tips Wizard

The Top 10 Tips Wizard highlights some of the most important capabilities of Acadia Infuse. Use it as a quick guide to get started.


Creating a New Source File

To create a new source file, choose New from the File menu (or click the new button on the toolbar). In the New dialog box, select the template on which to base the new file and click OK.

See Also

Modifying Templates


Opening a Source File

To open a source file, choose Open from the File menu (or click the Open button on the toolbar). Select a file from the Open dialog box and click OK.

You can also reopen files you have recently opened by selecting the file from the Reopen submenu, which is accessed from the File menu.


Saving a Source File

To save the active source file, choose Save from the File menu (or click the Save button on the toolbar). If you wish to save the file under a different name, choose the Save As menu option.

See Also

Saving All Opened Source Files


Saving All Opened Source Files

You can quickly save all source files you have opened in Acadia Infuse by choosing Save All from the File menu.


Reloading a Source File

To reload the contents of a source document from its disk file, choose Reload from the File menu. If you have modified the file since you last saved it, you will be prompted to confirm this action.


Printing a Source File

To print the current source file, choose Print from the File menu. A Print dialog box will ask you for the printing options.


Finding Text

You can search for text in the active source file by choosing Find from the Search menu (or by clicking the Find button on the toolbar).

Use the Find dialog box as follows:

•	Enter the text you wish to locate in the Find what box.

•	Check Match whole word only to locate text only if it matches a whole word.

•	Check Match case to locate text only if it exactly matches the capitalization of the text to find.

•	Specify the direction to search from the insertion point by selecting Up or Down in the Direction box.

•	Click the Find Next button to locate the next match.

•	Click the Close button to end the Find command.

Tip: After you have closed the Find dialog box, you can search for the same text by choosing Find Next from the Search menu or by clicking F3.


Replacing Text

You can replace text in the active source file by choosing Replace from the Search menu.

Use the Replace dialog box as follows:

•	Enter the text you wish to replace in the Find what box.

•	Enter the replacement text in the Replace with box.

•	Check Match whole word only to locate text only if it matches a whole word.

•	Check Match case to locate text only if it exactly matches the capitalization of the text to find.

•	Click the Find Next button to locate the next match.

•	Click the Replace button to replace the most recently found text with the replacement text.

•	Click the Replace All button to replace all instances of the find text with the replacement text.

•	Click the Close button to end the Replace command.

Tip:   To undo replacements that have already occurred, close the Replace dialog box and choose Undo from the Edit menu. If you have performed incremental replace operations, you will need to choose Undo for each of these actions. If you replaced all instances using Replace All, a single Undo will restore your changes.


Finding a Matching Brace

JavaScript uses brackets {} to encapsulate portions of code, such as a complete function or the if portion of an if..else statement. Each open bracket { must have a matching end bracket } or else you will get a syntax error. To determine a bracket’s match, use the Find Matching Brace from the Search menu (or click F4).


Jumping To a Line Number

You can jump to a specific line number in the active source file by choosing Goto Line from the Search menu. The Goto Line Number dialog box prompts you for the line number you want to find. When this dialog box is displayed, the current line number is shown in the box.

Note: The current line number and column number are displayed in the Line and Column Indicator on the status bar.


Setting a Bookmark

You can set a bookmark anywhere in the active source window by choosing Set Bookmark from the Search menu. This setting will mark the current location and return to it when you choose the Find Bookmark menu option.

Note: A bookmark remains in effect until you set a new bookmark or you close the source file window.

See Also

Finding a Bookmark


Finding a Bookmark

Choose Find Bookmark from the Search menu to locate the bookmark that you previously set using the Set Bookmark command.

See Also

Setting a Bookmark


Inserting HTML Tags

Acadia Infuse has several ways you can insert HTML tags into your source document:

•	Use the HTML toolbar to enter commonly used formatting tags into your code. To use, select the text you wish to tag and then click the appropriate toolbar button.

•	Use the HTML formatting menu commands found on the Insert menu. To use, select the text you wish to tag and then choose the desired menu command.

•	Use the HTML Tag Tree to drag-&-drop HTML tags into your source document.


Tiling Windows

To tile all opened source windows, choose Tile from the Window menu.


Cascading Windows

To cascade all opened source windows, choose Cascade from the Window menu.


Moving to the Next Window

If you have multiple opened source window, you can click the right arrow on the toolbar or press Ctrl+F6 to move to the next window in the window list.


Moving to the Previous Window

If you have multiple opened source window, you can click the left arrow on the toolbar or press Ctrl+F5 to move to the previous window in the window list.


About the Script Navigator

The Script Navigator gives you a visual treeview look at your source file and allows you to quickly jump to a function or object by double-clicking on the item.

See Also

Jumping to a Function Location

Jumping to an Object Location

Refreshing the Script Navigator


Jumping to a Function Location

To jump to the location of a function displayed in the Script Navigator, double-click its associated node in the Script Navigator’s Function tree. Acadia Infuse will position the cursor at the spot of the function.

Note: If you have defined a custom object, its constructor will be represented as a function in the Script Navigator, not as an object.


Jumping to an Object Location

To jump to the location of an object displayed in the Script Navigator, double-click its associated node in the Script Navigator’s Object tree. Acadia Infuse will position the cursor at the spot of the object.

Note: In Version 1.0, Acadia Infuse only places HTML-related JavaScript objects in the Script Navigator. Custom objects and built-in language objects are not represented in this treeview.


Refreshing the Script Navigator Tree

The Script Navigator automatically refreshes itself when you press Enter while in a source window. However, you can also manually refresh the Script Navigator by choosing Refresh Script Navigator from the View menu (or pressing F5).


About the JavaScript Object Tree

The JavaScript Object Tree serves several purposes for the JavaScript developer.

•	Use as a reference tool to locate the desired object, method, or property you need to use.

•	Use as a reference tool to see the interrelationships of the objects in the JavaScript object hierarchy.

•	Drag-&-drop an object or one of its methods or properties into your code.

•	Instantiate an object in your code.

•	View context-sensitive Help on each object, property, or method.


Inserting an Object Reference

You can insert a reference to a JavaScript object by dragging the object from the JavaScript Object Tree and dropping it into the desired position in the source document.

Tip: Double-clicking the object will place the object reference at the current insertion point.


Instantiating an Object

Some JavaScript objects need to be explicitly instantiated in your code before using them. Examples of these include the Array or String language objects as well as HTML-based objects, such as form and button objects.

You can instantiate any valid object by pressing the Ctrl key down while you perform a drag-&-drop action into your source document.

Note: Only a subset of JavaScript objects can be explicitly instantiated.  Performing this action on invalid objects will have no effect.


Inserting an Object's Property or Method
Inserting an Object’s Property or Method

You can insert a property or method of a JavaScript object by dragging the method or property from the JavaScript Object Tree and dropping it into the desired position in the source document.

In addition to the method or property being inserted, Acadia Infuse will also automatically add any additional information needed to correctly reference the language element. If that information is a variable, Acadia Infuse will automatically highlight the text for you to modify as needed.

Tip: Double-clicking the method or property will place the text at the current insertion point.


Obtaining JavaScript Language Help

Acadia Infuse integrates the official Netscape JavaScript Authoring Guide into its JavaScript Object and Language Trees. To receive Help on a specific language element, perform the following tasks:

1.	Click the right mouse button inside the JavaScript Object or Language Tree windows. A Help cursor will be displayed.

2.	Click on item you wish to reference. Help will be displayed on that language element in a popup window.

Tip: If you wish to cancel this process, click the Esc key while the Help cursor is displayed. The normal cursor will be restored.


About the JavaScript Language Tree

The JavaScript Language Tree provides access to JavaScript statements, operators, reserved words, and other language constructs. Using the JavaScript Language Tree, you can drag-&-drop language elements into your source document.

See Also

Inserting a Language Element

Inserting a Special Inline Character

Obtaining JavaScript Language Help


Inserting a Language Element

You can insert JavaScript language element from the JavaScript Language Tree into your source document. Drag the language element using your mouse and drop it into the desired position in the source document.

Tip: Double-clicking the language element will place the text at the current insertion point.


Inserting a Special Inline Character

JavaScript has special ways to handle certain characters, such as carriage returns or tabs, in your source code. The JavaScript Language Tree eliminates the need to remember the specific syntax issues when using these characters with its Inline Characters tree.

When you need to use one of these characters, drop the character declaration into your source document as a global variable and use as desired.


About the HTML Tag Tree

The HTML Tag Tree provides a way to drag-&-drop HTML tags into your source document.

See Also

Inserting an HTML Tag with the HTML Tag Tree

Inserting HTML Tags


Inserting an HTML Tag with the HTML Tag Tree

You can insert an HTML tag from the HTML Tag Tree into your source document. Drag the HTML tag using your mouse and drop it into the desired position in the source document.

Tip: Double-clicking the HTML tag will place the text at the current insertion point.


About the JavaScript Object Model

The JavaScript Object Model is a read-only view at the JavaScript object interrelationships. Whereas the JavaScript Object Tree located in the treeview pane of the Acadia Infuse window has full functionality, this floating toolbox is designed specifically to view the object hierarchy.

To view, choose JavaScript Object Model from the View menu.


About Frequent Scripts

Frequent Scripts enables you to drop in frequently used JavaScript and LiveWire code into your source file. Acadia Infuse comes with a library of pre-built code routines that developers can immediately take advantage of in their development process.

See Also

Inserting a Frequent Script

Adding a Frequent Script


Inserting a Frequent Script

To insert a frequent script into your source document, choose Frequent Scripts from the Insert menu (or click the Frequent Scripts button on the toolbar). Select the code snippet of your choice from the Frequent Scripts dialog box and click OK to paste the code into the current insertion point in the editing window.

Hint: Double-clicking the script selection in the list will automatically click the OK button for you.

Tip: In an editor window, you can select Insert Frequent Script from the popup menu to display the Frequent Scripts dialog box.


Adding a Frequent Script

To add piece of your code into the Frequent Scripts library, follow the instructions below:

1.	Highlight the code you wish to add in the current source document.

2.	Right-click to display the editor popup menu.

3.	Select the Add Frequent Script command.

4.	Enter the desired information in the Add to Frequent Scripts dialog box.

5.	Click OK.


Previewing Source Files

An important part of the JavaScript development process is previewing your scripts in a browser. Acadia Infuse closely integrates with Netscape Navigator and Microsoft Internet Explorer, but also allows you to add other browsers as desired.

See Also

Previewing a File in Netscape Navigator

Previewing a File in Microsoft Internet Explorer

Using the Tools | Preview Command


Previewing a File in Netscape Navigator

You can preview a source file in Netscape Navigator by choosing Preview Netscape Navigator from the Tools menu (or clicking the Netscape Navigator button on the toolbar).

Hint: To change the default size of the preview window, see the Preview tab in the Preferences dialog box.


Previewing a File in Microsoft Internet Explorer

You can preview a source file in Microsoft Internet Explorer by choosing Preview Microsoft Internet Explorer from the Tools menu (or clicking the Microsoft Internet Explorer button on the toolbar).

Hint: To change the default size of the preview window, see the Preview tab in the Preferences dialog box.


Toolbar

The toolbar provide a shortcut to many commonly performed tasks. To hide either the Standard or HTML toolbars, uncheck the associated menu command in the View menu.

Tip:  Right-clicking a toolbar will display a popup menu that allows you to hide/show either toolbar.

See Also

Moving a Toolbar


Moving a Toolbar

By default, the toolbars are anchored to the top of the Acadia Infuse window. However, you can make an anchored toolbar a floating toolbar (and vise versa) by double-clicking on a blank area on the toolbar. Alternatively, you can press down on a blank area of the toolbar with your mouse and drag the toolbar to the desired location.

You can anchor either toolbar on the top, bottom, left, or right of the window. Additionally, depending on whether you let go of the mouse button in your drag process, a toolbar can either be on the left or right of the treeview pane of the parent window.


Status Bar

The status bar displays various information about the editing environment. To hide the status bar, uncheck the Status Bar option from the View menu.

•	The first section of the status bar shows the current line and column as well as the total number of lines. Hint: Double-clicking this section will display the Go to Line Number dialog box.

•	The second section denotes Modified if the current source document has been modified since it was last saved.

•	The third section denotes whether you are in Insert or Overwrite mode.

•	The remaining two sections denote the state of your Caps and Num key settings.


Full View

You may have occasion to use the entire width of the Acadia Infuse window to work in an editor window. To remove the treeview pane from the left side of the window, check the Full View command from the View menu (or click F6). Toggle back to normal view by unchecking the Full View menu option (or clicking F6 again).


About Netscape LiveWire

Netscape LiveWire is Netscape’s tool suite that works in combination with Netscape servers. LiveWire uses JavaScript as its native server-side language.

For more information about LiveWire, choose LiveWire Information from the Web-Based Information submenu (located off of the Help menu).


Opening LiveWire Site Manager

Choose Run LiveWire Site Manager from the Tools menu (or the equivalent button on the toolbar) to open the LiveWire Site Manager utility.

Note: You must first specify the path for Site Manager on the LiveWire tab of the Preferences dialog box.


Using the LiveWire Compiler

Choose Compile LiveWire Application from the Tools menu (or the equivalent button on the toolbar) to display the Build LiveWire Application dialog box. Use this dialog box as an interface to the LiveWire command-line compiler.

After filling in the information in the Build LiveWire Application dialog box, click OK. Acadia Infuse will pass this information to the LiveWire compiler and attempt to compile the application. Please note that in Version 1.0, the DOS window does not remain opened after the compile attempt.

Note: You must first specify the path for the LiveWire compiler on the LiveWire tab of the Preferences dialog box.


About JavaScript

Excerpt from JavaScript Unleashed (Richard Wagner et al.), Sams.net Publishing

Like everything else connected to the Web, JavaScript is a new technology — even newer than the Java programming language itself.  JavaScript was initially developed by Netscape under the name of LiveScript.  This scripting language was intended to extend the capabilities of basic HTML and provide an alternative to using CGI scripts.  After Netscape saw Java, however, it began to work with Sun to provide a scripting language even closer linked to Java itself.  Hence, the name change to JavaScript.

One of the motivations behind JavaScript was the recognition of the need for logic to exist on the client, not only on the server.  With all logic on the server side, all processing is forced to go to the server, even for simple tasks such as data validation.  This leads to unnecessarily high contention for the server, and suboptimal performance.  In fact, without logic on the client side, the Web environment resembles the outdated terminal-to-host architecture of the 1980s that was replaced by the PC Revolution. Therefore, providing logic within the Web browser empowers the client side with local processing capability and makes the Web a true "client/server" architecture.

Java is a step in this direction, but it is implemented as an adjunct to HTML itself and is not intended to be integrated from a language standpoint.  Also, as a strongly typed language, Java is not optimal for gluing together divergent applets.  Java also required low-level programming skills, something that most HTML developers would rather avoid if all they need is to provide some logic behind HTML form elements.  Therefore, a higher-level client-side scripting language seemed like a natural missing piece in the Web development tool arena.

Since its rollout in December of 1995, JavaScript has drawn support from the major industry vendors, including (in addition to Sun and Netscape) Apple, Borland, Sybase, Informix, Oracle, Digital, HP, and IBM.  And while Microsoft is working on its own competitor to JavaScript called Visual Basic Script, Microsoft is supporting JavaScript in version 3.0 of Internet Explorer.

JavaScript is emerging as the standard Web scripting language.  As vendors produce Web development tools that require a scripting language, it is widely expected that JavaScript will often be used for that purpose.  The availability of tools that support JavaScript, such as Netscape’s LiveWire tool suite and Borland’s IntraBuilder, and tools that make it easier to work in JavaScript, such as Acadia Infuse, will help to increase the popularity of the language for every day Web development.


Ordering Acadia Infuse

Acadia Infuse is available from Acadia Software for $129.95. We accept major credit cards, checks, and money orders. To purchase Acadia Infuse, please use one of the following methods:

Credit Card

•	Online. Purchase online at the Acadia Software Web site (http://www.acadians.com/infuse) using CyberCash.

•	Fax. Fill out an order form from our Web site, print it on your printer, and fax it to 508/635-9211.

•	Telephone. Phone us at 508/264-4881.

Check/Money Order

•	Fill out an order form from our Web site, print it on your printer, and include form with your check or money order.


Obtaining Technical Support

If you require technical support, please use one of the following options:

•	Visit our Web site for latest technical support information and FAQ at http://www.acadians.com/infuse.

•	Email us at support@acadians.com. Along with your registration number, please provide a detailed message stating the questions or problems you have.

For information about Priority Support subscriptions, please see our Web site or contact infuse@acadians.com.

Note: Technical support is only provided on licensed copies of Acadia Infuse. If you have questions on the trial version, please visit our Web site or email infuse@acadians.com.


Modifying a Template File

The templates that are referred to in the File | New dialog box are located in the Template folder under the main Acadia Infuse folder (usually c:\Program Files\Acadia Software\Acadia Infuse). You can modify these files as desired and have the changes be used in future files based on these templates.


abs method

Returns the absolute value of a number.

Syntax

Math.abs(number)

number is any numeric expression or a property of an existing object.

Examples

In the following example, the user enters a number in the first text box and presses the Calculate button to display the absolute value of the number.

<FORM>
<P>Enter a number:
<INPUT TYPE="text" NAME="absEntry">
<P>The absolute value is:
<INPUT TYPE="text" NAME="result">
<P>
<INPUT TYPE="button" VALUE="Calculate"
   onClick="form.result.value = Math.abs(form.absEntry.value)">
</FORM>


acos method

Returns the arc cosine (in radians) of a number.

Syntax

Math.acos(number)

number is a numeric expression between -1 and 1, or a property of an existing object.

Description

The acos method returns a numeric value between 0 and pi radians. If the value of number is outside the suggested range, the return value is always 0.

Examples

// Displays the value 0document.write("The arc cosine of 1 is " + Math.acos(1))// Displays the value 3.141592653589793document.write("<P>The arc cosine of -1 is " + Math.acos(-1))// Displays the value 0document.write("<P>The arc cosine of 2 is " + Math.acos(2))


action property

A string specifying a destination URL for form data that is submitted.

Syntax

formName.action

formName is either the name of a form or an element in the forms array.

Description

The action property is a reflection of the ACTION attribute of the <FORM> tag. Each section of a URL contains different information. See the location object for a description of the URL components. You can set the action property at any time.

Examples

The following example sets the action property of the musicForm form to the value of the variable urlName:

document.musicForm.action=urlName


alert method

Displays an Alert dialog box with a message and an OK button.

Syntax

alert("message")

message is any string or a property of an existing object.

Description

Use the alert method to display a message that does not require a user decision. The message argument specifies a message that the dialog box contains.

Although alert is a method of the window object, you do not need to specify a windowReference when you call it. For example, windowReference.alert() is unnecessary.

Examples

In the following example, the testValue() function checks the name entered by a user in the text object of a form to make sure that it is no more than eight characters in length. This example uses the alert method to prompt the user to enter a valid value.

function testValue(textElement) {
   if (textElement.length > 8) {
      alert("Please enter a name that is 8 characters or less")
   }
}


alinkColor property

A string specifying the color of an active link (after mouse-button down, but before mouse-button up).

Syntax

document.alinkColor

Description

The alinkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in Color. This property is the JavaScript reflection of the ALINK attribute of the <BODY> tag. You cannot set this property after the HTML source has been through layout.

If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".

Examples

The following example sets the color of active links to aqua using a string literal:

document.alinkColor="aqua"

The following example sets the color of active links to aqua using a hexadecimal triplet:

document.alinkColor="00FFFF"


anchor method

Creates an HTML anchor that is used as a hypertext target.

Syntax

text.anchor(nameAttribute)

text is any string or a property of an existing object. nameAttribute is any string or a property of an existing object.

Description

Use the anchor method with the write or writeln methods to programatically create and display an anchor in a document. Create the anchor with the anchor method, then call write or writeln to display the anchor in a document.

In the syntax, the text string represents the literal text that you want the user to see. The nameAttribute string represents the NAME attribute of the <A> tag.

Anchors created with the anchor method become elements in the anchors array. See the anchor object for information about the anchors array.

Examples

The following example opens the msgWindow window and creates an anchor for the Table of Contents:

var myString="Table of Contents"

msgWindow=window.open("","displayWindow") msgWindow.document.writeln(myString.anchor("contents_anchor"))

msgWindow.document.close()


anchor object (anchors array)

A piece of text that can be the target of a hypertext link.

Syntax

To define an anchor, use standard HTML syntax:

<A [HREF=locationOrURL]
   NAME="anchorName"
   [TARGET="windowName"]>
   anchorText
</A>

HREF=locationOrURL identifies a destination anchor or URL. If this attribute is present, the anchor object is also a link object. See link for details.

NAME="anchorName" specifies a tag that becomes an available hypertext target within the current document.

TARGET="windowName" specifies the window that the link is loaded into. This attribute is meaningful only if HREF=locationOrURL is present. See link for details.

anchorText specifies the text to display at the anchor.

You can also define an anchor using the anchor method.

Description

If an anchor object is also a link object, the object has entries in both the anchors and links arrays.

The anchors array

You can reference the anchor objects in your code by using the anchors array. This array contains an entry for each <A> tag containing a NAME attribute in a document in source order. For example, if a document contains three named anchors, these anchors are reflected as document.anchors[0], document.anchors[1], and document.anchors[2].


anchors property

An array of objects corresponding to named anchors in source order. See anchor object.


appCodeName property

A string specifying the code name of the browser.

Syntax

navigator.appCodeName

Description

appCodeName is a read-only property.

Examples

The following example displays the value of the appCodeName property:

document.write("The value of navigator.appCodeName is " + navigator.appCodeName)

For Navigator 2.0, this displays the following:

The value of navigator.appCodeName is Mozilla


appName property

A string specifying the name of the browser.

Syntax

navigator.appName

Description

appName is a read-only property.

Examples

The following example displays the value of the appName property:

document.write("The value of navigator.appName is " + navigator.appName)

For Navigator 2.0, this displays the following:

The value of navigator.appName is Netscape


appVersion property

A string specifying version information for the Navigator.

Syntax

navigator.appVersion

Description

The appVersion property specifies version information in the following format:releaseNumber (platform; country)

The values contained in this format are the following:

releaseNumber is the version number of the Navigator. For example, "2.0b4" specifies Navigator 2.0, beta 4.

platform is the platform upon which the Navigator is running. For example, "Win16" specifies a 16-bit version of Windows such as Windows 3.11.

country is either "I" for the international release, or "U" for the domestic U.S. release. The domestic release has a stronger encryption feature than the international release.

appVersion is a read-only property.

Examples

The following example displays version information for the Navigator:

document.write("The value of navigator.appVersion is " + navigator.appVersion)

For Navigator 2.0 on Windows 95, this displays the following:

The value of navigator.appVersion is 2.0 (Win95, I)


asin method

Returns the arc sine (in radians) of a number.

Syntax

Math.asin(number)
number is a numeric expression between -1 and 1, or a property of an existing object.

Description

The asin method returns a numeric value between -pi/2 and pi/2 radians. If the value of number is outside the suggested range, the return value is always 0.

Examples

// Displays the value 1.570796326794897 (pi/2)
document.write("The arc sine of 1 is " + Math.asin(1))

// Displays the value -1.570796326794897 (-pi/2)
document.write("<P>The arc sine of -1 is " + Math.asin(-1))

// Displays the value 0 because the argument is out of range
document.write("<P>The arc sine of 2 is " + Math.asin(2))


atan method

Returns the arc tangent (in radians) of a number.

Syntax

Math.atan(number)

number is either a numeric expression or a property of an existing object, representing the tangent of an angle.

Description

The atan method returns a numeric value between -pi/2 and pi/2 radians.

Examples

// Displays the value 0.7853981633974483
document.write("The arc tangent of 1 is " + Math.atan(1))

// Displays the value -0.7853981633974483
document.write("<P>The arc tangent of -1 is " + Math.atan(-1))

// Displays the value 0.4636476090008061
document.write("<P>The arc tangent of .5 is " + Math.atan(.5))


back method

Loads the previous URL in the history list.

Syntax

history.back()

Description

This method performs the same action as a user choosing the Back button in the Navigator. The back method is the same as history.go(-1).

Examples

The following custom buttons perform the same operations as the Navigator Back and Forward buttons:

<P><INPUT TYPE="button" VALUE=" Back"
   onClick="history.back()">
<P><INPUT TYPE="button" VALUE="> Forward"
   onClick="history.forward()">


bgColor property

A string specifying the color of the document background.

Syntax

document.bgColor

Description

The bgColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in Color. This property is the JavaScript reflection of the BGCOLOR attribute of the <BODY> tag. The default value of this property is set by the user on the Colors tab of the Preferences dialog box, which is displayed by choosing General Preferences from the Options menu.

You can set the bgColor property at any time.

If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".

Examples

The following example sets the color of the document background to aqua using a string literal:

document.bgColor="aqua"

The following example sets the color of the document background to aqua using a hexadecimal triplet:

document.bgColor="00FFFF"


big method

Causes a string to be displayed in a big font as if it were in a <BIG> tag.

Syntax

stringName.big()
stringName is any string or a property of an existing object.

Description

Use the big method with the write or writeln methods to format and display a string in a document.

Examples

The following example uses string methods to change the size of a string:

var worldString="Hello, world"
document.write(worldString.small())
document.write("<P>" + worldString.big())
document.write("<P>" + worldString.fontsize(7))


blink method

Causes a string to blink as if it were in a <BLINK> tag.

Syntax

stringName.blink()
stringName is any string or a property of an existing object.

Description

Use the blink method with the write or writeln methods to format and display a string in a document.

Examples

The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"
document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())


blur method

Removes focus from the specified object.

Syntax

passwordName.blur()

frameReference.focus()

windowReference.blur()

Description

Use the blur method to remove focus from a specific form element.

In JavaScript 1.1, the blur method is also a method of the frame and window objects. The blur method removes focus from the window or frame. Removing focus sends a window to the background in most windowing systems.

Examples

The following example removes focus from the password element userPass:

userPass.blur()

This example assumes that the password is defined as:

<INPUT TYPE="password" NAME="userPass">


bold method

Causes a string to be displayed as bold as if it were in a <B> tag.

Syntax

stringName.bold()
stringName is any string or a property of an existing object.

Description

Use the bold method with the write or writeln methods to format and display a string in a document.

Examples

The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"
document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())

The previous example produces the same output as the following HTML:

<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>


button object

A pushbutton on an HTML form.

Syntax

To define a button:

<INPUT TYPE="button"
   NAME="buttonName"
   VALUE="buttonText"
   [onClick="handlerText"]>

NAME="buttonName" specifies the name of the button object. You can access this value using the name property.

VALUE="buttonText" specifies the label to display on the button face. You can access this value using the value property.

buttonName is the value of the NAME attribute of a button object.

formName is either the value of the NAME attribute of a form object or an element in the forms array.

index is an integer representing a button object on a form.

propertyName is one of the properties listed below. methodName is one of the methods listed below.

Description

A button object is a form element and must be defined within a <FORM> tag.

The button object is a custom button that you can use to perform an action you define. The button executes the script specified by its onClick event handler.


ceil method

Returns the least integer greater than or equal to a number.

Syntax

Math.ceil(number)
number is any numeric expression or a property of an existing object.

Examples

//Displays the value 46
document.write("The ceil of 45.95 is " + Math.ceil(45.95))

//Displays the value -45
document.write("<P>The ceil of -45.95 is " + Math.ceil(-45.95))


charAt method

Returns the character at the specified index.

Syntax

stringName.charAt(index)
stringName is any string or a property of an existing object.

index is any integer from 0 to stringName.length - 1, or a property of an existing object.

Description

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character is stringName.length - 1. If the index you supply is out of range, JavaScript returns an empty string.

Examples

The following example displays characters at different locations in the string "Brave new world".

var anyString="Brave new world"
document.write("The character at index 0 is " + anyString.charAt(0))
document.write("The character at index 1 is " + anyString.charAt(1))
document.write("The character at index 2 is " + anyString.charAt(2))
document.write("The character at index 3 is " + anyString.charAt(3))
document.write("The character at index 4 is " + anyString.charAt(4))


checkbox object

A checkbox on an HTML form. A checkbox is a toggle switch that lets the user set a value on or off.

Syntax

To define a checkbox, use standard HTML syntax with the addition of the onClick event handler:

<INPUT
   TYPE="checkbox"
   NAME="checkboxName"
   VALUE="checkboxValue"
   [CHECKED]
   [onClick="handlerText"]>
   textToDisplay

NAME="checkboxName" specifies the name of the checkbox object. You can access this value using the name property.

VALUE="checkboxValue" specifies a value that is returned to the server when the checkbox is selected and the form is submitted. This defaults to "on". You can access this value using the value property.

CHECKED specifies that the checkbox is displayed as checked. You can access this value using the defaultChecked property.

textToDisplay specifies the label to display beside the checkbox.

Description

A checkbox object is a form element and must be defined within a <FORM> tag.

Use the checked property to specify whether the checkbox is currently checked. Use the defaultChecked property to specify whether the checkbox is checked when the form is loaded.


checked property

A Boolean value specifying the selection state of a checkbox object or radio button.

Syntax

1. checkboxName.checked
2. radioName[index].checked

checkboxName is either the value of the NAME attribute of a checkbox object or an element in the elements array.

radioName is the value of the NAME attribute of a radio object.

index is an integer representing a radio button in a radio object.

Description

If a checkbox or radio button is selected, the value of its checked property is true; otherwise, it is false. You can set the checked property at any time. The display of the checkbox or radio button updates immediately when you set the checked property.

Examples

The following example examines an array of radio buttons called musicType on the musicForm form to determine which button is selected. The VALUE attribute of the selected button is assigned to the checkedButton variable.

function stateChecker() {
   var checkedButton = ""
   for (var i in document.musicForm.musicType) {
      if (document.musicForm.musicType[i].checked=="1") {
         checkedButton=document.musicForm.musicType[i].value
      }
   }
}


clear method

Clears the document in a window.

Syntax

document.clear()

Description

The clear method empties the content of a window, regardless of how the content of the window has been painted.

Examples

When the following function is called, the clear method empties the contents of the msgWindow window:

function windowCleaner() {
   msgWindow.document.clear()
   msgWindow.document.close()
}


clearTimeout method

Cancels a timeout that was set with the setTimeout method.

Syntax

clearTimeout(timeoutID)
timeoutID is a timeout setting that was returned by a previous call to the setTimeout method.


click method

Simulates a mouse click on the calling form element.

Syntax

1. buttonName.click()
2. radioName[index].click()
3. checkboxName.click()

buttonName is either the value of the NAME attribute of a button, reset, or submit object or an element in the elements array.

radioName is the value of the NAME attribute of a radio object or an element in the elements array.

index is an integer representing a radio button in a radio object.

checkboxName is either the value of the NAME attribute of a checkbox object or an element in the elements array.

Description

The effect of the click method varies according to the calling element:

For button, reset, and submit, performs the same action as clicking the button.

For a radio, selects a radio button.

For a checkbox, checks the checkbox and sets its value to on.

Examples

The following example toggles the selection status of the first radio button in the musicType radio object on the musicForm form:

document.musicForm.musicType[0].click()

The following example toggles the selection status of the newAge checkbox on the musicForm form:

document.musicForm.newAge.click()


close method (document object)

Closes an output stream and forces data sent to layout to display.

Syntax

document.close()

Description

The close method closes a stream opened with the document.open() method. If the stream was opened to layout, the close method forces the content of the stream to display. Font style tags, such as <BIG> and <CENTER>, automatically flush a layout stream. The close method also stops the "meteor shower" in the Netscape icon and displays "Document: Done" in the status bar.

Examples

The following function calls document.close() to close a stream that was opened with document.open(). The document.close() method forces the content of the stream to display in the window.

function windowWriter1() {
   var myString = "Hello, world!"
   msgWindow.document.open()
   msgWindow.document.write(myString + "<P>")
   msgWindow.document.close()
}


close method (window object)

Closes the specified window.

Syntax

windowReference.close()
windowReference is a valid way of referring to a window, as described in the window object.

Description

The close method closes the specified window. If you call close without specifying a windowReference, JavaScript closes the current window. In event handlers, you must specify window.close() instead of simply using close(). Due to the scoping of static objects in JavaScript, a call to close() without specifying an object name is equivalent to document.close().

In JavaScript 1.1, the close method now closes only windows opened by JavaScript using the open method. If you attempt to close any other window, a confirm is generated, which lets the user choose whether the window closes. This is a security feature to prevent "mail bombs" containing self.close(). However, if the window has only one document (the current one) in its session history, the close is allowed without any confirm. This is a special case for one-off windows that need to open other windows and then dispose of themselves.

Examples

The following example closes the messageWin window:

messageWin.close()

This example assumes that the window was opened in a manner similar to the following:

messageWin=window.open("")


confirm method

Displays a Confirm dialog box with the specified message and OK and Cancel buttons.

Syntax

confirm("message")

message is any string or a property of an existing object.

Description

Use the confirm method to ask the user to make a decision that requires either an OK or a Cancel. The message argument specifies a message that prompts the user for the decision. The confirm method returns true if the user chooses OK and false if the user chooses Cancel. Although confirm is a method of the window object, you do not need to specify a windowReference when you call it. For example, windowReference.confirm() is unnecessary.

Examples

This example uses the confirm method in the confirmCleanUp() function to confirm that the user of an application really wants to quit. If the user chooses OK, the custom cleanUp() function closes the application.

function confirmCleanUp() {
   if (confirm("Are you sure you want to quit this application?")) {
      cleanUp()
   }
}

You can call the confirmCleanUp() function in the onClick event handler of a form's pushbutton, as shown in the following example:

<INPUT TYPE="button" VALUE="Quit" onClick="confirmCleanUp()">


cookie property

String value of a cookie, which is a small piece of information stored by the Navigator in the cookies.txt file.

Syntax

document.cookie

Description

Use string methods such as substring, charAt, indexOf, and lastIndexOf to determine the value stored in the cookie. See the Netscape for a complete specification of the cookie syntax.You can set the cookie property at any time.

Examples

The following function uses the cookie property to record a reminder for users of an application. The "expires=" component sets an expiration date for the cookie, so it persists beyond the current browser session. The format of the date must be

Wdy, DD-Mon-YY HH:MM:SS GMT

where Wdy is the full name of the day of the week, DD is an integer representation of the day of the month, Mon is the month, YY is the last two digits of the year, and HH, MM, and SS are two-digit representations of hours, minutes, and seconds, respectively. This is the same date format as returned by Date.toGMTString, except: (1) Dashes are added between the day, month, and year ; (2) Year is two-digit for cookies.

For example, a valid cookie expiration date is: expires=Wednesday, 09-Nov-99 23:12:40 GMT

function RecordReminder(time, expression) {
   // Record a cookie of the form "@<T>=<E>" to map
   // from <T> in milliseconds since the epoch,
   //  returned by Date.getTime(), onto an encoded expression,
   // <E> (encoded to contain no white space, semicolon,
   // or comma characters)
   document.cookie = "@" + time + "=" + expression + ";"
   // set the cookie expiration time to one day
   // beyond the reminder time
   document.cookie += "expires=" + cookieDate(time + 24*60*60*1000)
   // cookieDate is a function that formats the date according to the cookie spec
}

When the user loads the page that contains this function, another function uses indexOf("@") and indexOf("=") to determine the date and time stored in the cookie.


cos method

Returns the cosine of a number.

Syntax

Math.cos(number)
number is a numeric expression representing the size of an angle in radians, or a property of an existing object.

Description

The cos method returns a numeric value between -1 and 1, which represents the cosine of the angle.

Examples

//Displays the value 6.123031769111886e-017
document.write("The cosine of PI/2 radians is " + Math.cos(Math.PI/2))

//Displays the value -1
document.write("<P>The cosine of PI radians is " + Math.cos(Math.PI))

//Displays the value 1
document.write("<P>The cosine of 0 radians is " + Math.cos(0))

<SCRIPT> document.write("Last modified " + document.lastModified)</SCRIPT>


Date object

Lets you work with dates and times.

Syntax

To create a Date object:

1. dateObjectName = new Date()
2. dateObjectName = new Date("month day, year hours:minutes:seconds")
3. dateObjectName = new Date(year, month, day)
4. dateObjectName = new Date(year, month, day, hours, minutes, seconds)

dateObjectName is either the name of a new object or a property of an existing object. month, day, year, hours, minutes, and seconds are string values for form 2 of the syntax. For forms 3 and 4, they are integer values.

To use Date methods:

dateObjectName.methodName(parameters)
dateObjectName is either the name of an existing Date object or a property of an existing object.. methodName is one of the methods listed below.

Exceptions: The Date object's parse and UTC methods are static methods that you use as follows:

Date.UTC(parameters)
Date.parse(parameters)

Description

The Date object is a built-in JavaScript object. Form 1 of the syntax creates today's date and time. If you omit hours, minutes, or seconds from form 2 or 4 of the syntax, the value will be set to zero. The way JavaScript handles dates is very similar to the way Java handles dates: both languages have many of the same date methods, and both store dates internally as the number of milliseconds since January 1, 1970 00:00:00. Dates prior to 1970 are not allowed.

Examples

today = new Date()

birthday = new Date("December 17, 1995 03:24:00")

birthday = new Date(95,12,17)

birthday = new Date(95,12,17,3,24,0)


defaultChecked property

A Boolean value indicating the default selection state of a checkbox or radio button.

Syntax

1. checkboxName.defaultChecked
2. radioName[index].defaultChecked

checkboxName is either the value of the NAME attribute of a checkbox object or an element in the elements array. radioName is the value of the NAME attribute of a radio object. index is an integer representing a radio button in a radio object.

Description

If an checkbox or radio button is selected by default, the value of the defaultChecked property is true; otherwise, it is false. defaultChecked initially reflects whether the CHECKED attribute is used within an <INPUT> tag; however, setting defaultChecked overrides the CHECKED attribute. You can set the defaultChecked property at any time. The display of the checkbox or radio button does not update when you set the defaultChecked property, only when you set the checked property.

Examples

The following example resets an array of radio buttons called musicType on the musicForm form to the default selection state.

function radioResetter() {
   var i=""
   for (i in document.musicForm.musicType) {
      if (document.musicForm.musicType[i].defaultChecked==true) {
         document.musicForm.musicType[i].checked=true
      }
   }
}


defaultSelected property

A Boolean value indicating the default selection state of an option in a select object.

Syntax

selectName.options[index].defaultSelected
selectName is either the value of the NAME attribute of a select object or an element in the elements array.

index is an integer representing an option in a select object.

Description

If an option in a select object is selected by default, the value of the defaultSelected property is true; otherwise, it is false. defaultSelected initially reflects whether the SELECTED attribute is used within an <OPTION> tag; however, setting defaultSelected overrides the SELECTED attribute. You can set the defaultSelected property at any time. The display of the select object does not update when you set the defaultSelected property, only when you set the selected or selectedIndex properties. A select object created without the MULTIPLE attribute can have only one option selected by default. When you set defaultSelected in such an object, any previous default selections, including defaults set with the SELECTED attribute, are cleared. If you set defaultSelected in a select object created with the MULTIPLE attribute, previous default selections are not affected.

In JavaScript 1.1, the defaultSelected property is now a property of the Option object.

Examples

In the following example, the restoreDefault() function returns the musicType select object to its default state. The for loop uses the options array to evaluate every option in the select object. The if statement sets the selected property if defaultSelected is true.

function restoreDefault() {
   for (var i = 0; i  document.musicForm.musicType.length; i++) {
      if (document.musicForm.musicType.options[i].defaultSelected == true) {
         document.musicForm.musicType.options[i].selected=true
      }
   }
}

The previous example assumes that the select object is similar to the following:

<SELECT NAME="musicType">
   <OPTION SELECTED> R&B
   <OPTION> Jazz
   <OPTION> Blues
   <OPTION> New Age
</SELECT>


defaultStatus property

The default message displayed in the status bar at the bottom of the window.

Syntax

windowReference.defaultStatus

windowReference is a valid way of referring to a window, as described in the window object.

Description

The defaultStatus message appears when nothing else is in the status bar. Do not confuse the defaultStatus property with the status property. The status property reflects a priority or transient message in the status bar, such as the message that appears when a mouseOver event occurs over an anchor. You can set the defaultStatus property at any time. You must return true if you want to set the defaultStatus property in the onMouseOver event handler.

Examples

In the following example, the statusSetter() function sets both the status and defaultStatus properties in an onMouseOver event handler:

function statusSetter() {
   window.defaultStatus = "Click the link for the Netscape home page"
   window.status = "Netscape home page"
}

<A HREF="http://www.netscape.com"
   onMouseOver = "statusSetter(); return true">Netscape</A>

In the previous example, notice that the onMouseOver event handler returns a value of true. You must return true to set status or defaultStatus in an event handler.


defaultValue property

A string indicating the default value of a password, text, or textarea object.

Syntax

1. passwordName.defaultValue
2. textName.defaultValue
3. textareaName.defaultValue
passwordName is either the value of the NAME attribute of a password object or an element in the elements array.

textName is either the value of the NAME attribute of a text object or an element in the elements array.

textareaName is either the value of the NAME attribute of a textarea object or an element in the elements array.

Description

The initial value of defaultValue differs for each object:

For text objects, it initially reflects the value of the VALUE attribute.

For textarea objects, it initially reflects the value specified between the <TEXTAREA> and </TEXTAREA> tags.

For password objects, it initially is null (for security reasons), regardless of the value of the VALUE attribute.

Setting defaultValue programatically overrides the initial setting. If you programatically set defaultValue for the password object and then evaluate it, JavaScript returns the current value. You can set the defaultValue property at any time. The display of the related object does not update when you set the defaultValue property, only when you set the value property.

Examples

The following function evaluates the defaultValue property of objects on the surfCity form and displays the values in the msgWindow window:

function defaultGetter() {
   msgWindow=window.open("")
   msgWindow.document.write("hidden.defaultValue is " +
      document.surfCity.hiddenObj.defaultValue + "<BR>")
   msgWindow.document.write("password.defaultValue is " +
      document.surfCity.passwordObj.defaultValue + "<BR>")
   msgWindow.document.write("text.defaultValue is " +
      document.surfCity.textObj.defaultValue + "<BR>")
   msgWindow.document.write("textarea.defaultValue is " +
      document.surfCity.textareaObj.defaultValue + "<BR>")
   msgWindow.document.close()
}


document object

Contains information on the current document, and provides methods for displaying HTML output to the user.

Syntax

To define a document object, use standard HTML syntax:

<BODY
   BACKGROUND="backgroundImage"
   BGCOLOR="backgroundColor"
   TEXT="foregroundColor"
   LINK="unfollowedLinkColor"
   ALINK="activatedLinkColor"
   VLINK="followedLinkColor"
   [onLoad="handlerText"]
   [onUnload="handlerText"]>
</BODY>

BACKGROUND specifies an image that fills the background of the document.

BGCOLOR, TEXT, LINK, ALINK, and VLINK are color specifications expressed as a hexadecimal RGB triplet (in the format "rrggbb" or "#rrggbb") or as one of the string literals listed in Color.

Description

An HTML document consists of a <HEAD> and <BODY> tag. The <HEAD> includes information on the document's title and base (the absolute URL base to be used for relative URL links in the document). The <BODY> tag encloses the body of a document, which is defined by the current URL. The entire body of the document (all other HTML elements for the document) goes within the <BODY> tag. You can load a new document by using the location object. You can reference the anchors, forms, and links of a document by using the anchors, forms, and links arrays. These arrays contain an entry for each anchor, form, or link in a document.


E property

Euler's constant and the base of natural logarithms, approximately 2.718.

Syntax

Math.E

Description

Because E is a constant, it is a read-only property of Math.

Examples

The following example displays Euler's constant:

document.write("Euler's constant is " + Math.E)


elements array

An array of objects corresponding to form elements (such as checkbox, radio, and text objects) in source order.

Syntax

1. formName.elements[index]
2. formName.elements.length
formName is either the name of a form or an element in the forms array.

index is an integer representing an object on a form.

Description

You can reference a form's elements in your code by using the elements array. This array contains an entry for each object (button, checkbox, hidden, password, radio, reset, select, submit, text, or textarea object) in a form in source order. For example, if a form has a text field and two checkboxes, these elements are reflected as formName.elements[0], formName.elements[1], and formName.elements[2].

Although you can also reference a form's elements by using the element's name (from the NAME attribute), the elements array provides a way to reference form objects programatically without using their names. For example, if the first object on the userInfo form is the userName text object, you can evaluate it in either of the following ways:

userInfo.userName.value
userInfo.elements[0].value

To obtain the number of elements on a form, use the length property: formName.elements.length. Each radio button in a radio object appears as a separate element in the elements array. Elements in the elements array are read-only. For example, the statement formName.elements[0]="music" has no effect. The value of each element in the elements array is the full HTML statement for the object.


elements property

An array of objects corresponding to form elements (such as checkbox, radio, and text objects) in source order.


encoding property

A string specifying the MIME encoding of the form.

Syntax

formName.encoding
formName is either the name of a form or an element in the forms array.

Description

The encoding property initially reflects the ENCTYPE attribute of the <FORM> tag; however, setting encoding overrides the ENCTYPE attribute. You can set the encoding property at any time. Certain values of the encoding property may require specific values for other form properties. See RFC for more information.

Examples

The following function returns the value of the musicForm encoding property:

function getEncoding() {
   return document.musicForm.encoding
}


escape function

Returns the ASCII encoding of an argument in the ISO Latin-1 character set.

Syntax

escape("string")
string is a non-alphanumeric string in the ISO Latin-1 character set, or a property of an existing object.

Description

The escape function is not a method associated with any object, but is part of the language itself. The value returned by the escape function is a string of the form "%xx", where xx is the ASCII encoding of a character in the argument. If you pass the escape function an alphanumeric character, the escape function returns the same character.

Examples

The following example returns "%26"

escape("&")

The following example returns "%21%23"

escape("!#")


eval function

The eval function evaluates a string and returns a value.

Syntax

eval(string)
string is any string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.

Description

The eval function is a built-in JavaScript function. It is not a method associated with any object, but is part of the language itself. The argument of the eval function is a string. Do not call eval to evaluate an arithmetic expression. JavaScript evaluates arithmetic expressions automatically. If the argument represents an expression, eval evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements. If you construct an arithmetic expression as a string, you can use eval to evaluate it at a later time. For example, suppose you have a variable x. You can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval at a later point in your script.

Examples

Both of the write statements below display 42. The first evaluates the string "x + y + 1", and the second evaluates the string "42".

var x = 2
var y = 39
var z = "42"
document.write(eval("x + y + 1"), "<BR>")
document.write(eval(z), "<BR>")


exp method

Returns enumber, where number is the argument, and e is Euler's constant, the base of the natural logarithms.

Syntax

Math.exp(number)
number is any numeric expression or a property of an existing object.

Examples

//Displays the value 2.718281828459045
document.write("The value of e<SUP>1</SUP> is " + Math.exp(1))


fgColor property

A string specifying the color of the document text.

Syntax

document.fgColor

Description

The fgColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in Color. This property is the JavaScript reflection of the TEXT attribute of the <BODY> tag. The default value of this property is set by the user on the Colors tab of the Preferences dialog box, which is displayed by choosing General Preferences from the Options menu. You cannot set this property after the HTML source has been through layout.

If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".

You can override the value set in the fgColor property in either of the following ways:

Setting the COLOR attribute of the <FONT> tag.

Using the fontcolor method.

Examples

The following example sets the color of the foreground text to aqua using a string literal:

document.fgColor="aqua"

The following example sets the color of the foreground text to aqua using a hexadecimal triplet:

document.fgColor="00FFFF"


fixed method

Causes a string to be displayed in fixed-pitch font as if it were in a <TT> tag.

Syntax

stringName.fixed()
stringName is any string or a property of an existing object.

Description

Use the fixed method with the write or writeln methods to format and display a string in a document.

Examples

The following example uses the fixed method to change the formatting of a string:

var worldString="Hello, world"
document.write(worldString.fixed())

The previous example produces the same output as the following HTML:

<TT>Hello, world</TT>


floor method

Returns the greatest integer less than or equal to a number.

Syntax

Math.floor(number)
number is any numeric expression or a property of an existing object.

Examples

//Displays the value 45
document.write("<P>The floor of 45.95 is " + Math.floor(45.95))

//Displays the value -46
document.write("<P>The floor of -45.95 is " + Math.floor(-45.95))


focus method

Gives focus to the specified object.

Syntax

1. passwordName.focus()
2. selectName.focus()
3. textName.focus()
4. textareaName.focus()

passwordName is either the value of the NAME attribute of a password object or an element in the elements array. selectName is either the value of the NAME attribute of a select object or an element in the elements array. textName is either the value of the NAME attribute of a text object or an element in the elements array. textareaName is either the value of the NAME attribute of a textarea object or an element in the elements array.

Description

Use the focus method to navigate to a specific form element and give it focus. You can then either programatically enter a value in the element or let the user enter a value.

In JavaScript 1.1, the focus method is now a method of the frame and window objects. The focus method gives focus to a window or frame. Giving focus brings a window forward in most windowing systems.

Examples

In the following example, the checkPassword function confirms that a user has entered a valid password. If the password is not valid, the focus method returns focus to the password object and the select method highlights it so the user can re-enter the password.

function checkPassword(userPass) {
   if (badPassword) {
      alert("Please enter your password again.")
      userPass.focus()
      userPass.select()
   }
}

This example assumes that the password is defined as:

<INPUT TYPE="password" NAME="userPass">


fontcolor method

Causes a string to be displayed in the specified color as if it were in a <FONT COLOR=color> tag.

Syntax

stringName.fontcolor(color)
stringName is any string or a property of an existing object.

color is a string or a property of an existing object, expressing the color as a hexadecimal RGB triplet or as one of the string literals listed in Color.

Description

Use the fontcolor method with the write or writeln methods to format and display a string in a document.If you express color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072". The fontcolor method overrides a value set in the fgColor property.

Examples

The following example uses the fontcolor method to change the color of a string

var worldString="Hello, world"
document.write(worldString.fontcolor("maroon") +
   " is maroon in this line")
document.write("<P>" + worldString.fontcolor("salmon") +
   " is salmon in this line")
document.write("<P>" + worldString.fontcolor("red") +
   " is red in this line")
document.write("<P>" + worldString.fontcolor("8000") +
   " is maroon in hexadecimal in this line")
document.write("<P>" + worldString.fontcolor("FA8072") +
   " is salmon in hexadecimal in this line")
document.write("<P>" + worldString.fontcolor("FF00") +
   " is red in hexadecimal in this line")

The previous example produces the same output as the following HTML:

<FONT COLOR="maroon">Hello, world</FONT> is maroon in this line
<P><FONT COLOR="salmon">Hello, world</FONT> is salmon in this line
<P><FONT COLOR="red">Hello, world</FONT> is red in this line
<FONT COLOR="8000">Hello, world</FONT> is maroon in hexadecimal in this line
<P><FONT COLOR="FA8072">Hello, world</FONT> is salmon in hexadecimal in this line
<P><FONT COLOR="FF00">Hello, world</FONT> is red in hexadecimal in this line


fontsize method

Causes a string to be displayed in the specified font size as if it were in a <FONTSIZE=size> tag.

Syntax

stringName.fontsize(size)
stringName is any string or a property of an existing object.

size is an integer between one and seven, or a string representing a signed integer between 1 and 7, or a property of an existing object.

Description

Use the fontsize method with the write or writeln methods to format and display a string in a document. When you specify size as an integer, you set the size of stringName to one of the seven defined sizes. When you specify size as a string such as "-2", you adjust the font size of stringName relative to the size set in the <BASEFONT> tag.

Examples

The following example uses string methods to change the size of a string:

var worldString="Hello, world"
document.write(worldString.small())
document.write("<P>" + worldString.big())
document.write("<P>" + worldString.fontsize(7))

The previous example produces the same output as the following HTML:

<SMALL>Hello, world</SMALL>
<P><BIG>Hello, world</BIG>
<P><FONTSIZE=7>Hello, world</FONTSIZE>


form object (forms array)

Lets users input text and make choices from form objects such as checkboxes, radio buttons, and selection lists. You can also use a form to post data to a server.

Syntax

To define a form, use standard HTML syntax with the addition of the onSubmit event handler:

<FORM
   NAME="formName"
   TARGET="windowName"
   ACTION="serverURL"
   METHOD=GET | POST
   ENCTYPE="encodingType"
   [onSubmit="handlerText"]>
</FORM>

Description

Each form in a document is a distinct object. You can reference a form's elements in your code by using the element's name (from the NAME attribute) or the elements array. The elements array contains an entry for each element (such as a checkbox, radio, or text object) in a form.

The forms array

You can reference the forms in your code by using the forms array (you can also use the form name). This array contains an entry for each form object (<FORM> tag) in a document in source order. For example, if a document contains three forms, these forms are reflected as document.forms[0], document.forms[1], and document.forms[2].


forms property

An array of objects corresponding to the forms (<FORM> tags) in a document in source order. See form object.


forward method

Loads the next URL in the history list.

Syntax

history.forward()

Description

This method performs the same action as a user choosing the Forward button in the Navigator. The forward method is the same as history.go(1).

Examples

The following custom buttons perform the same operations as the Navigator Back and Forward buttons:

<P><INPUT TYPE="button" VALUE=" Back"
   onClick="history.back()">
<P><INPUT TYPE="button" VALUE="> Forward"
   onClick="history.forward()">


frame object (frames array)

A window that can display multiple, independently scrollable frames on a single screen, each with its own distinct URL. Frames can point to different URLs and be targeted by other URLs, all within the same screen. A series of frames makes up a page.

Syntax

To define a frame object, use standard HTML syntax. The onLoad and onUnload event handlers are specified in the <FRAMESET> tag but are actually event handlers for the window object:

<FRAMESET
   ROWS="rowHeightList"
   COLS="columnWidthList"
   [onLoad="handlerText"]
   [onUnload="handlerText"]>
   [<FRAME SRC="locationOrURL" NAME="frameName">]
</FRAMESET>

Description

The <FRAMESET> tag is used in an HTML document whose sole purpose is to define the layout of frames that make up a page. Each frame is a window object. If a <FRAME> tag contains SRC and NAME attributes, you can refer to that frame from a sibling frame by using parent.frameName or parent.frames[index].

The frames array

You can reference the frame objects in your code by using the frames array. This array contains an entry for each child frame (<FRAME> tag) in a window containing a <FRAMESET> tag in source order. For example, if a window contains three child frames, these frames are reflected as parent.frames[0], parent.frames[1], and parent.frames[2].


frames property

An array of objects corresponding to child frames (<FRAME> tag) in source order. See frame object.


getDate method

Returns the day of the month for the specified date.

Syntax

dateObjectName.getDate()
dateObjectName is either the name of a date object or a property of an existing object.

Description

The value returned by getDate is an integer between 1 and 31.

Examples

The second statement below assigns the value 25 to the variable day, based on the value of the date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:00")
day = Xmas95.getDate()


getDay method

Returns the day of the week for the specified date.

Syntax

dateObjectName.getDay()
dateObjectName is either the name of a date object or a property of an existing object.

Description

The value returned by getDay is an integer corresponding to the day of the week: zero for Sunday, one for Monday, two for Tuesday, and so on.

Examples

The second statement below assigns the value 1 to weekday, based on the value of the date object Xmas95. This is because December 25, 1995 is a Monday.

Xmas95 = new Date("December 25, 1995 23:15:00")
weekday = Xmas95.getDay()


getHours method

Returns the hour for the specified date.

Syntax

dateObjectName.getHours()
dateObjectName is either the name of a date object or a property of an existing object.

Description

The value returned by getHours is an integer between 0 and 23.

Examples

The second statement below assigns the value 23 to the variable hours, based on the value of the date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:00")
hours = Xmas95.getHours()


getMinutes method

Returns the minutes in the specified date.

Syntax

dateObjectName.getMinutes()
dateObjectName is either the name of a date object or a property of an existing object.

Description

The value returned by getMinutes is an integer between 0 and 59.

Examples

The second statement below assigns the value 15 to the variable minutes, based on the value of the date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:00")
minutes = Xmas95.getMinutes()


getMonth method

Returns the month in the specified date.

Syntax

dateObjectName.getMonth()
dateObjectName is either the name of a date object or a property of an existing object.

Description

The value returned by getMonth is an integer between zero and eleven. Zero corresponds to January, one to February, and so on.

Examples

The second statement below assigns the value 11 to the variable month, based on the value of the date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:00")
month = Xmas95.getDate()


getSeconds method

Returns the seconds in the current time.

Syntax

dateObjectName.getSeconds()
dateObjectName is either the name of a date object or a property of an existing object.

Description

The value returned by getSeconds is an integer between 0 and 59.

Examples

The second statement below assigns the value 30 to the variable secs, based on the value of the date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:30")
secs = Xmas95.getSeconds()


getTime method

Returns the numeric value corresponding to the time for the specified date.

Syntax

dateObjectName.getTime()
dateObjectName is either the name of a date object or a property of an existing object.

Description

The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00. You can use this method to help assign a date and time to another date object.

Examples

The following example assigns the date value of theBigDay to sameAsBigDay.

theBigDay = new Date("July 1, 1999")
sameAsBigDay = new Date()
sameAsBigDay.setTime(theBigDay.getTime())


getTimezoneOffset method

Returns the time zone offset in minutes for the current locale.

Syntax

dateObjectName.getTimezoneOffset()
dateObjectName is either the name of a date object or a property of an existing object.

Description

The time zone offset is the difference between local time and GMT. Daylight savings time prevents this value from being a constant.

Examples

x = new Date()
currentTimeZoneOffsetInHours = x.getTimezoneOffset()/60


getYear method

Returns the year in the specified date.

Syntax

dateObjectName.getYear()
dateObjectName is either the name of a date object or a property of an existing object.

Description

The value returned by getYear is the year less 1900. For example, if the year is 1976, the value returned is 76.

Examples

The second statement below assigns the value 95 to the variable year, based on the value of the date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:00")
year = Xmas95.getYear()


go method

Loads a URL from the history list.

Syntax

history.go(delta | "location")
delta is an integer or a property of an existing object, representing a relative position in the history list.

location is a string or a property of an existing object, representing all or part of a URL in the history list.

Description

The go method navigates to the location in the history list determined by the argument that you specify. You can interactively display the history list by choosing History from the Window menu. Up to 10 items in the history list are also displayed on the Go menu. The delta argument is a positive or negative integer. If delta is greater than zero, the go method loads the URL that is that number of entries forward in the history list; otherwise, it loads the URL that is that number of entries backward in the history list. If delta is 0, Navigator reloads the current page. The location argument is a string. Use location to load the nearest history entry whose URL contains location as a substring. The location to URL matching is case-insensitive. Each section of a URL contains different information. See the location object for a description of the URL components.

Examples

The following button navigates to the nearest history entry that contains the string "home.netscape.com":

<P><INPUT TYPE="button" VALUE="Go"
   onClick="history.go('home.netscape.com')">

The following button navigates to the URL that is three entries backward in the history list:

<P><INPUT TYPE="button" VALUE="Go"
   onClick="history.go(-3)">


hash property

A string beginning with a hash mark (#) that specifies an anchor name in the URL.

Syntax

1. links[index].hash
2. location.hash
index is an integer representing a link object.

Description

The hash property specifies a portion of the URL.

You can set the hash property at any time, although it is safer to set the href property to change a location. If the hash that you specify cannot be found in the current location, you will get an error.

See RFC for complete information about the hash.


hidden object

A text object that is suppressed from form display on an HTML form. A hidden object is used for passing name/value pairs when a form submits.

Syntax

To define a hidden object:

<INPUT
   TYPE="hidden"
   NAME="hiddenName"
   [VALUE="textValue"]>

NAME="hiddenName" specifies the name of the hidden object. You can access this value using the name property. VALUE="textValue" specifies the initial value of the hidden object.

Description

A hidden object is a form element and must be defined within a <FORM> tag. A hidden object cannot be seen or modified by a user, but you can programatically change the value of the object by changing its value property. You can use hidden objects for client/server communication.


history object

Contains information on the URLs that the client has visited within a window. This information is stored in a history list, and is accessible through the Navigator's Go menu.

Syntax

To use a history object:

1. history.propertyName
2. history.methodName(parameters)
propertyName is one of the properties listed below. methodName is one of the methods listed below.

document

Description

The history object is a linked list of URLs the user has visited, as shown in the Navigator's Go menu.

Examples

Example 1. The following example goes to the URL the user visited three clicks ago in the current window:

window.history.go(-3)

Example 2. You can use the history object with a specific window or frame. The following example causes window2 to go back one item in its window (or session) history:

window2.history.back()


host property

A string specifying the hostname:port portion of the URL.

Syntax

1. links[index].host
2. location.host
index is an integer representing a link object.

Description

The host property specifies a portion of the URL. The host property is the concatenation of the hostname and port properties, separated by a colon. When the port property is null, the host property is the same as the hostname property. You can set the host property at any time, although it is safer to set the href property to change a location. If the host that you specify cannot be found in the current location, you will get an error. See Section 3.1 of RFC for complete information about the hostname and port.


hostname property

A string specifying the host and domain name, or IP address, of a network host.

Syntax

1. links[index].hostname
2. location.hostname
index is an integer representing a link object.

Description

The hostname property specifies a portion of the URL. The hostname property is a substring of the host property. The host property is the concatenation of the hostname and port properties, separated by a colon. When the port property is null, the host property is the same as the hostname property. You can set the hostname property at any time, although it is safer to set the href property to change a location. If the hostname that you specify cannot be found in the current location, you will get an error. See Section 3.1 of RFC for complete information about the hostname.


href property

A string specifying the entire URL.

Syntax

1. links[index].href
2. location.href
index is an integer representing a link object.

Description

The href property specifies the entire URL. Other location object properties are substrings of the href property. You can set the href property at any time. Omitting a property name from the location object is equivalent to specifying location.href. For example, the following two statements are equivalent and set the URL of the current window to the Netscape home page: window.location.href="http://www.netscape.com/"

window.location="http://www.netscape.com/"


index property

An integer representing the index of an option in a select object.

Syntax

selectName.options[indexValue].index
selectName is either the value of the NAME attribute of a select object or an element in the elements array.

indexValue is an integer representing an option in a select object.

Description

The number identifying the position of the option in the selection, starting from zero.


indexOf method

Returns the index within the calling string object of the first occurrence of the specified value, starting the search at fromIndex.

Syntax

stringName.indexOf(searchValue, [fromIndex])
stringName is any string or a property of an existing object.

searchValue is a string or a property of an existing object, representing the value to search for.

fromIndex is the location within the calling string to start the search from. It can be any integer from 0 to stringName.length - 1 or a property of an existing object.

Description

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character is stringName.length - 1.If you do not specify a value for fromIndex, JavaScript assumes 0 by default. If searchValue is not found, JavaScript returns -1.

Examples

The following example uses indexOf and lastIndexOf to locate values in the string "Brave new world".

var anyString="Brave new world"
//Displays 8
document.write("<P>The index of the first w from the beginning is " +
   anyString.indexOf("w"))
//Displays 10
document.write("<P>The index of the first w from the end is " +
   anyString.lastIndexOf("w"))
//Displays 6
document.write("<P>The index of 'new' from the beginning is " +
   anyString.indexOf("new"))
//Displays 6
document.write("<P>The index of 'new' from the end is " +
   anyString.lastIndexOf("new"))


isNaN function

On Unix platforms, evaluates an argument to determine if it is "NaN" (not a number).

Syntax

isNaN(testValue)
testValue is the value you want to evaluate.

Description

The isNaN function is a built-in JavaScript function. It is not a method associated with any object, but is part of the language itself. isNaN is available on Unix platforms only. On all platforms except Windows, the parseFloat and parseInt functions return "NaN" when they evaluate a value that is not a number. The "NaN" value is not a number in any radix. You can call the isNaN function to determine if the result of parseFloat or parseInt is "NaN". If "NaN" is passed on to arithmetic operations, the operation results will also be "NaN". The isNaN function returns true or false.

Examples

The following example evaluates floatValue to determine if it is a number, then calls a procedure accordingly.

floatValue=parseFloat(toFloat)
if isNaN(floatValue) {
   notFloat()
} else {
   isFloat()
}


italics method

Causes a string to be italicized as if it were in an <I> tag.

Syntax

stringName.italics()
stringName is any string or a property of an existing object.

Description

Use the italics method with the write or writeln methods to format and display a string in a document.

Examples

The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"
document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())

The previous example produces the same output as the following HTML:

<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>


lastIndexOf method

Returns the index within the calling string object of the last occurrence of the specified value. The calling string is searched backwards, starting at fromIndex.

Syntax

stringName.lastIndexOf(searchValue, [fromIndex])
stringName is any string or a property of an existing object.

searchValue is a string or a property of an existing object, representing the value to search for.

fromIndex is the location within the calling string to start the search from. It can be any integer from 0 to stringName.length - 1 or a property of an existing object.

Description

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character is stringName.length - 1.If you do not specify a value for fromIndex, JavaScript assumes stringName.length - 1 (the end of the string) by default. If searchValue is not found, JavaScript returns -1.

Examples

The following example uses indexOf and lastIndexOf to locate values in the string "Brave new world".

var anyString="Brave new world"
//Displays 8
document.write("<P>The index of the first w from the beginning is " +
   anyString.indexOf("w"))
//Displays 10
document.write("<P>The index of the first w from the end is " +
   anyString.lastIndexOf("w"))
//Displays 6
document.write("<P>The index of 'new' from the beginning is " +
   anyString.indexOf("new"))
//Displays 6
document.write("<P>The index of 'new' from the end is " +
   anyString.lastIndexOf("new"))


lastModified property

A string representing the date that a document was last modified.

Syntax

document.lastModified

Description

lastModified is a read-only property.

Examples

In the following example, the lastModified property is used in a <SCRIPT> tag at the end of an HTML file to display the modification date of the page:

document.write("This page updated on " + document.lastModified)


length property

An integer that specifies a length-related feature of the calling object or array.

Examples

In the following example, the getChoice() function uses the length property to iterate over every element in the musicType array. musicType is a select element on the musicForm form.

function getChoice() {
   for (var i = 0; i  document.musicForm.musicType.length; i++) {
      if (document.musicForm.musicType.options[i].selected == true) {
         return document.musicForm.musicType.options[i].text
      }
   }
}

The following example displays 8 in an alert dialog box:

var x="Netscape"
alert("The string length is " + x.length)


link method

Creates an HTML hypertext link that jumps to another URL.

Syntax

linkText.link(hrefAttribute)

linkText is any string or a property of an existing object. hrefAttribute is any string or a property of an existing object.

Description

Use the link method with the write or writeln methods to programatically create and display a hypertext link in a document. Create the link with the link method, then call write or writeln to display the link in a document. In the syntax, the linkText string represents the literal text that you want the user to see. The hrefAttribute string represents the HREF attribute of the <A> tag, and it should be a valid URL. Each section of a URL contains different information. See the location object for a description of the URL components. Links created with the link method become elements in the links array. See the link object for information about the links array.

Examples

The following example displays the word "Netscape" as a hypertext link that returns the user to the Netscape home page:

var hotText="Netscape"
var URL="http://www.netscape.com"
document.open()
document.write("Click to return to " + hotText.link(URL))
document.close()

The previous example produces the same output as the following HTML:

Click to return to <A HREF="http://www.netscape.com">Netscape</A>


link object (links array)

A piece of text or an image identified as a hypertext link. When the user clicks the link text, the link hypertext reference is loaded into its target window.

Syntax

To define a link, use standard HTML syntax with the addition of the onClick and onMouseOver event handlers:

<A HREF=locationOrURL
   [NAME="anchorName"]
   [TARGET="windowName"]
   [onClick="handlerText"]
   [onMouseOver="handlerText"]>
   linkText
</A>

Description

Each link object is a location object and has the same properties as a location object. If a link object is also an anchor object, the object has entries in both the anchors and links arrays. When a user clicks a link object and navigates to the destination document (specified by HREF=locationOrURL), the destination document's referrer property contains the URL of the source document. Evaluate the referrer property from the destination document.

The links array

You can reference the link objects in your code by using the links array. This array contains an entry for each link object (<A HREF=""> tag) in a document in source order. For example, if a document contains three link objects, these links are reflected as document.links[0], document.links[1], and document.links[2].


linkColor property

A string specifying the color of the document hyperlinks.

Syntax

document.linkColor

Description

The linkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in Color. This property is the JavaScript reflection of the LINK attribute of the <BODY> tag. The default value of this property is set by the user on the Colors tab of the Preferences dialog box, which is displayed by choosing General Preferences from the Options menu. You cannot set this property after the HTML source has been through layout. If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".

Examples

The following example sets the color of document links to aqua using a string literal:

document.linkColor="aqua"

The following example sets the color of document links to aqua using a hexadecimal triplet:

document.linkColor="00FFFF"


links property

An array of objects corresponding to link objects in source order. See link object.


LN2 property

The natural logarithm of two, approximately 0.693.

Syntax

Math.LN2

Description

Because LN2 is a constant, it is a read-only property of Math.

Examples

The following example displays the natural log of 2:

document.write("The natural log of 2 is " + Math.LN2)


LN10 property

The natural logarithm of ten, approximately 2.302.

Syntax

Math.LN10

Description

Because LN10 is a constant, it is a read-only property of Math.

Examples

The following example displays the natural log of 10:

document.write("The natural log of 10 is " + Math.LN10)


location object

Contains information on the current URL.

Syntax

To use a location object:

[windowReference.]location[.propertyName]

windowReference is a variable windowVar from a window definition (see window object), or one of the synonyms top or parent.

propertyName is one of the properties listed below. Omitting the property name is equivalent to specifying the href property (the complete URL).

Description

The location object represents a complete URL. Each property of the location object represents a different portion of the URL. The following diagram of a URL shows the relationships between the location properties:

protocol//hostname:port pathname search hash


location property

A string specifying the complete URL of the document.

Syntax

document.location

Description

Do not confuse the location property of the document object with the location object. You cannot change the value of the location property (document.location), but you can change the value of the location object's properties (window.location.propertyName). document.location is a string-valued property that usually matches what window.location.href is set to when you load the document, but redirection may change it. location is a read-only property of document.

Examples

The following example displays the URL of the current document:

document.write("The current URL is " + document.location)


log method

Returns the natural logarithm (base e) of a number.

Syntax

Math.log(number)

number is any positive numeric expression or a property of an existing object.

Description

If the value of number is outside the suggested range, the return value is always -1.797693134862316e+308.

Examples

//Displays the value 2.302585092994046
document.write("The natural log of 10 is " + Math.log(10))

//Displays the value 0
document.write("<P>The natural log of 1 is " + Math.log(1))

//Displays the value -1.797693134862316e+308
//because the argument is out of range
document.write("<P>The natural log of 0 is " + Math.log(0))


LOG2E property

The base 2 logarithm of e (approximately 1.442).

Syntax

Math.LOG2E

Description

Because LOG2E is a constant, it is a read-only property of Math.

Examples

The following example displays the base 2 logarithm of E:

document.write("The base 2 logarithm of E is " + Math.LOG2E)


LOG10E property

The base 10 logarithm of e (approximately 0.434).

Syntax

Math.LOG10E

Description

Because LOG10E is a constant, it is a read-only property of Math.

Examples

The following example displays the base 10 logarithm of E:

document.write("The base 10 logarithm of E is " + Math.LOG10E)


Math object

A built-in object that has properties and methods for mathematical constants and functions. For example, the Math object's PI property has the value of pi.

Syntax

To use a Math object:

1. Math.propertyName
2. Math.methodName(parameters)

propertyName is one of the properties listed below. methodName is one of the methods listed below.

None.

Description

The Math object is a built-in JavaScript object. You reference the constant PI as Math.PI. Constants are defined with the full precision of real numbers in JavaScript.Similarly, you reference Math functions as methods. For example, the sine function is Math.sin(argument), where argument is the argument.It is often convenient to use the with statement when a section of code uses several Math constants and methods, so you don't have to type "Math" repeatedly. For example,

with (Math) {
   a = PI * r*r
   y = r*sin(theta)
   x = r*cos(theta)
}


max method

Returns the greater of two numbers.

Syntax

Math.max(number1, number2)

number1 and number2 are any numeric arguments or the properties of existing objects.

Math

Examples

//Displays the value 20
document.write("The maximum value is " + Math.max(10,20))

//Displays the value -10
document.write("<P>The maximum value is " + Math.max(-10,-20))


method property

A string specifying how form field input information is sent to the server.

Syntax

formName.method

formName is either the name of a form or an element in the forms array.

form

Description

The method property is a reflection of the METHOD attribute of the <FORM> tag. The method property should evaluate to either "get" or "post". You can set the method property at any time. Certain values of the method property may require specific values for other form properties. See RFC for more information.

Examples

The following function returns the value of the musicForm method property:

function getMethod() {
  return document.musicForm.method
}


min method

Returns the lesser of two numbers.

Syntax

Math.min(number1, number2)

number1 and number2 are any numeric arguments or the properties of existing objects.

Examples

//Displays the value 10
document.write("
The minimum value is " + Math.min(10,20))

//Displays the value -20
document.write("<P>The minimum value is " + Math.min(-10,-20))


name property

A string specifying the name of an object.

Examples

In the following example, the valueGetter() function uses a for loop to iterate over the array of elements on the valueTest form. The msgWindow window displays the names of all the elements on the form:

newWindow=window.open("http://www.netscape.com")

function valueGetter() {
   var msgWindow=window.open("")
   for (var i = 0; i  newWindow.document.valueTest.elements.length; i++) {
      msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
   }
}

In the following example, the first statement creates a window called netscapeWin. The second statement displays the value "netscapeHomePage" in the alert dialog box, because "netscapeHomePage" is the value of the windowName argument of netscapeWin.

netscapeWin=window.open("http://www.netscape.com", "netscapeHomePage")
alert(netscapeWin.name)


navigator object

Contains information about the version of Navigator in use.

Syntax

To use a navigator object:

navigator.propertyName

propertyName is one of the properties listed below.

Description

Use the navigator object to determine which version of the Navigator your users have.


onBlur event handler

A blur event occurs when a select, text, or textarea field on a form loses focus. The onBlur event handler executes JavaScript code when a blur event occurs.See the relevant objects for the onBlur syntax.

Examples

In the following example, userName is a required text field. When a user attempts to leave the field, the onBlur event handler calls the required() function to confirm that userName has a legal value.

<INPUT TYPE="text" VALUE="" NAME="userName" onBlur="required(this.value)">


onChange event handler

A change event occurs when a select, text, or textarea field loses focus and its value has been modified. The onChange event handler executes JavaScript code when a change event occurs.Use the onChange event handler to validate data after it is modified by a user.See the relevant objects for the onChange syntax.

Event Handler of

select, text, textarea

Examples

In the following example, userName is a text field. When a user attempts to leave the field, the onBlur event handler calls the checkValue() function to confirm that userName has a legal value.

<INPUT TYPE="text" VALUE="" NAME="userName" onBlur="checkValue(this.value)">


nBlur , onFocus event handlers
onBlur , onFocus event handlers


onClick event handler

A click event occurs when an object on a form is clicked. The onClick event handler executes JavaScript code when a click event occurs.See the relevant objects for the onClick syntax.

Event Handler of

button, checkbox, radio, link, reset, submit

Examples

For example, suppose you have created a JavaScript function called compute(). You can execute the compute() function when the user clicks a button by calling the function in the onClick event handler, as follows:

<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">

In the above example, the keyword this refers to the current object; in this case, the Calculate button. The construct this.form refers to the form containing the button.For another example, suppose you have created a JavaScript function called pickRandomURL() that lets you select a URL at random. You can use the onClick event handler of a link to specify a value for the HREF attribute of the <A> tag dynamically, as shown in the following example: Go!In the above example, the onMouseOver event handler specifies a custom message for the Navigator status bar when the user places the mouse pointer over the Go! anchor. As this example shows, you must return true to set the window.status property in the onMouseOver event handler.


onFocus event handler

A focus event occurs when a field receives input focus by tabbing with the keyboard or clicking with the mouse. Selecting within a field results in a select event, not a focus event. The onFocus event handler executes JavaScript code when a focus event occurs.See the relevant objects for the onFocus syntax.

Event Handler of

select, text, textarea

Examples

The following example uses an onFocus handler in the valueField textarea object to call the valueCheck() function.

<INPUT TYPE="textarea" VALUE="" NAME="valueField" onFocus="valueCheck()">


nBlur , onChange event handlers
onBlur , onChange event handlers


onLoad event handler

A load event occurs when Navigator finishes loading a window or all frames within a <FRAMESET>. The onLoad event handler executes JavaScript code when a load event occurs. Use the onLoad event handler within either the <BODY> or the <FRAMESET> tag, for example, <BODY onLoad="...">. In a <FRAMESET> and <FRAME> relationship, an onLoad event within a frame (placed in the <BODY> tag) occurs before an onLoad event within the <FRAMESET> (placed in the <FRAMESET> tag).

Event Handler of

window

Examples

In the following example, the onLoad event handler displays a greeting message after a web page is loaded.

<BODY onLoad="window.alert("Welcome to the Brave New World home page!")>


nUnload event handler
onUnload event handler


onMouseOver event handler

A mouseOver event occurs once each time the mouse pointer moves over an object from outside that object. The onMouseOver event handler executes JavaScript code when a mouseOver event occurs.You must return true within the event handler if you want to set the status or defaultStatus properties with the onMouseOver event handler.See the relevant objects for the onMouseOver syntax.

Event Handler of

link

Examples

By default, the HREF value of an anchor displays in the status bar at the bottom of the Navigator when a user places the mouse pointer over the anchor. In the following example, the onMouseOver event handler provides the custom message "Click this if you dare." ClickSee onClick for an example of using onMouseOver when the <A> tag's HREF attribute is set dynamically.


onSelect event handler

A select event occurs when a user selects some of the text within a text or textarea field. The onSelect event handler executes JavaScript code when a select event occurs.See the relevant objects for the onSelect syntax.

Event Handler of

text, textarea

Examples

The following example uses an onSelect handler in the valueField text object to call the selectState() function.

<INPUT TYPE="text" VALUE="" NAME="valueField" onSelect="selectState()">


onSubmit event handler

A submit event occurs when a user submits a form. The onSubmit event handler executes JavaScript code when a submit event occurs. You can use the onSubmit event handler to prevent a form from being submitted; to do so, put a return statement that returns false in the event handler. Any other returned value lets the form submit. If you omit the return statement, the form is submitted. See the relevant objects for the onSubmit syntax.

Event Handler of

form

Examples

In the following example, the onSubmit event handler calls the formData() function to evaluate the data being submitted. If the data is valid, the form is submitted; otherwise, the form is not submitted.

form.onSubmit="return formData(this)"

See also the examples for the form object.


ubmit object
submit object

submit method


onUnload event handler

An unload event occurs when you exit a document. The onUnload event handler executes JavaScript code when an unload event occurs. Use the onUnload event handler within either the <BODY> or the <FRAMESET> tag, for example, <BODY onUnload="...">. In a <FRAMESET> and <FRAME> relationship, an onUnload event within a frame (placed in the <BODY> tag) occurs before an onUnload event within the <FRAMESET> (placed in the <FRAMESET> tag).

Event Handler of

window

Examples

In the following example, the onUnload event handler calls the cleanUp() function to perform some shut down processing when the user exits a web page:

<BODY onUnload="cleanUp()">


open method (document object)

Opens a stream to collect the output of write or writeln methods.

Syntax

document.open(["mimeType"])

Description

The open method opens a stream to collect the output of write or writeln methods. If the mimeType is text or image, the stream is opened to layout; otherwise, the stream is opened to a plug-in. If a document exists in the target window, the open method clears it. End the stream by using the document.close() method.

Examples

The following function calls document.open() to open a stream before issuing a write method:

function windowWriter1() {
   var myString = "Hello, world!"
   msgWindow.document.open()
   msgWindow.document.write("<P>" + myString)
   msgWindow.document.close()
}

In the following example, the probePlugIn() function determines whether a user has the Shockwave plug-in installed:

function probePlugIn(mimeType) {
   var havePlugIn = false
   var tiny = window.open("", "teensy", "width=1,height=1")
   if (tiny != null) {
      if (tiny.document.open(mimeType) != null)
         havePlugIn = true
      tiny.close()
   }
   return havePlugIn
}
var haveShockwavePlugIn = probePlugIn("application/x-director")


open method (window object)

Opens a new web browser window.

Syntax

[windowVar = ][window].open("URL", "windowName", ["windowFeatures"])

windowVar is the name of a new window. Use this variable when referring to a window's properties, methods, and containership.

URL specifies the URL to open in the new window. See the location object for a description of the URL components.

windowName is the window name to use in the TARGET attribute of a <FORM> or <A> tag. windowName can contain only alphanumeric or underscore (_) characters.

windowFeatures is a comma-separated list of any of the following options and values:

   toolbar[=yes|no]|[=1|0]
   location[=yes|no]|[=1|0]
   directories[=yes|no]|[=1|0]
   status[=yes|no]|[=1|0]
   menubar[=yes|no]|[=1|0]
   scrollbars[=yes|no]|[=1|0]
   resizable[=yes|no]|[=1|0]
   width=pixels
   height=pixels

You may use any subset of these options. Separate options with a comma. Do not put spaces between the options.pixels is a positive integer specifying the dimension in pixels.

Description

The open method opens a new web browser window on the client, similar to choosing New Web Browser from the File menu of the Navigator.


options property

An array corresponding to options in a select object (<OPTION> tags) in source order.


parent property

The parent property is a synonym for a window or frame whose frameset contains the current frame.

Syntax

1. parent.propertyName
2. parent.methodName
3. parent.frameName
4. parent.frames[index]

propertyName is the defaultStatus, status, length, name, or parent property when the calling parent refers to a window object. propertyName is the length, name, or parent property when the calling parent refers to a frame object. methodName is any method associated with the window object. frameName and frames[index] are ways to refer to frames.

frame, window

Description

The parent property refers to the <FRAMESET> window of a frame. Child frames within a frameset refer to sibling frames by using "parent" in place of the window name as follows: parent.frameName or parent.frames[index]. For example, if the fourth frame in a set has NAME="homeFrame", sibling frames can refer to that frame using parent.homeFrame or parent.frames[3]. You can use parent.parent to refer to the "grandparent" frame or window when a <FRAMESET> tag is nested within a child frame. The parent property is read-only. The value of the parent property is

<object nameAttribute>

where nameAttribute is the NAME attribute if the parent is a frame, or an internal reference if the parent is a window.


parse method

Returns the number of milliseconds in a date string since January 1, 1970 00:00:00, local time.

Syntax

Date.parse(dateString)

dateString is a string representing a date or a property of an existing object.

Description

The parse method takes a date string (such as "Dec 25, 1995"), and returns the number of milliseconds since January 1, 1970 00:00:00 (local time). This function is useful for setting date values based on string values, for example in conjunction with the setTime method and the Date object.Given a string representing a time, parse returns the time value. It accepts the IETF standard date syntax: "Mon, 25 Dec 1995 13:30:00 GMT". It understands the continental US time zone abbreviations, but for general use, use a time zone offset, for example "Mon, 25 Dec 1995 13:30:00 GMT+0430" (4 hours, 30 minutes west of the Greenwich meridian). If you do not specify a time zone, the local time zone is assumed. GMT and UTC are considered equivalent. Because the parse function is a static method of Date, you always use it as Date.parse(), rather than as a method of a date object you created.

Examples

If IPOdate is an existing date object, then

IPOdate.setTime(Date.parse("Aug 9, 1995"))


parseFloat function

Parses a string argument and returns a floating point number.

Syntax

parseFloat(string)

string is a string that represents the value you want to parse.

Description

The parseFloat function is a built-in JavaScript function. It is not a method associated with any object, but is part of the language itself. parseFloat parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign ( + or -), numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters. If the first character cannot be converted to a number, parseFloat returns one of the following values:

0 on Windows platforms.

"NaN" on any other platform, indicating that the value is not a number. For arithmetic purposes, the "NaN" value is not a number in any radix. You can call the isNaN function to determine if the result of parseFloat is "NaN". If "NaN" is passed on to arithmetic operations, the operation results will also be "NaN".

Examples

The following examples all return 3.14:

parseFloat("3.14")
parseFloat("314e-2")
parseFloat("0.0314E+2")
var x = "3.14"
parseFloat(x)

The following example returns "NaN" or 0:

parseFloat("FF2")


parseInt function

Parses a string argument and returns an integer of the specified radix or base.

Syntax

parseInt(string [,radix])

string is a string that represents the value you want to parse.

radix is an integer that represents the radix of the return value.

Description

The parseInt function is a built-in JavaScript function. It is not a method associated with any object, but is part of the language itself. The parseInt function parses its first argument, a string, and attempts to return an integer of the specified radix (base). For example, a radix of 10 indicates to convert to a decimal number, 8 octal, 16 hexadecimal, and so on. For radixes above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used. If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. ParseInt truncates numbers to integer values.


password object

A text field on an HTML form that conceals its value by displaying asterisks (*). When the user enters text into the field, asterisks (*) hide anything entered from view.

Syntax

To define a password object, use standard HTML syntax:

<INPUT
   TYPE="password"
   NAME="passwordName"
   [VALUE="textValue"]
   SIZE=integer>

NAME="passwordName" specifies the name of the password object. You can access this value using the name property.

VALUE="textValue" specifies the initial value of the password object. You can access this value using the defaultValue property.

SIZE=integer specifies the number of characters the password object can accommodate without scrolling.

Description

A password object is a form element and must be defined within a <FORM> tag.


pathname property

A string specifying the url-path portion of the URL.

Syntax

1. links[index].pathname
2. location.pathname

index is an integer representing a link object.

Description

The pathname property specifies a portion of the URL. The pathname supplies the details of how the specified resource can be accessed. You can set the pathname property at any time, although it is safer to set the href property to change a location. If the pathname that you specify cannot be found in the current location, you will get an error. See Section 3.1 of RFC for complete information about the pathname.


PI property

The ratio of the circumference of a circle to its diameter, approximately 3.14159.

Syntax

Math.PI

Description

Because PI is a constant, it is a read-only property of Math.

Examples

The following example displays the value of pi:

document.write("The value of pi is " + Math.PI)


port property

A string specifying the communications port that the server uses for communications.

Syntax

1. links[index].port
2. location.port

index is an integer representing a link object.

Description

The port property specifies a portion of the URL. The port property is a substring of the host property. The host property is the concatenation of the hostname and port properties, separated by a colon. When the port property is not defined, the host property is the same as the hostname property. You can set the port property at any time, although it is safer to set the href property to change a location. If the port that you specify cannot be found in the current location, you will get an error. If the port property is not specified, it defaults to 80 on the server. See Section 3.1 of RFC for complete information about the port.


pow method

Returns base to the exponent power, that is, baseexponent.

Syntax

Math.pow(base, exponent)

base is any numeric expression or a property of an existing object. exponent is any numeric expression or a property of an existing object. If the result would include an imaginary number (for example pow(-1, 0.5)), then the value returned is always zero.

Examples

//Displays the value 49
document.write("7 to the power of 2 is " + Math.pow(7,2))

//Displays the value 1024
document.write("<P>2 to the power of 10 is " + Math.pow(2,10))


prompt method

Displays a Prompt dialog box with a message and an input field.

Syntax

prompt(message, [inputDefault])

message is any string or a property of an existing object; the string is displayed as the message. inputDefault is a string, integer, or property of an existing object that represents the default value of the input field.

Description

Use the prompt method to display a dialog box that receives user input. If you do not specify an initial value for inputDefault, the dialog box displays the value <undefined>. Although prompt is a method of the window object, you do not need to specify a windowReference when you call it. For example, windowReference.prompt() is unnecessary.

Examples

prompt("Enter the number of cookies you want to order:", 12)


protocol property

A string specifying the beginning of the URL, up to and including the first colon.

Syntax

1. links[index].protocol
2. location.protocol

index is an integer representing a link object.

Description

The protocol property specifies a portion of the URL. The protocol indicates the access method of the URL. For example, a protocol of "http:" specifies Hypertext Transfer Protocol, and a protocol of "javascript:" specifies JavaScript code. You can set the protocol property at any time, although it is safer to set the href property to change a location. If the protocol that you specify cannot be found in the current location, you will get an error. The protocol property represents the scheme name of the URL. See Section 2.1 of RFC for complete information about the protocol.


radio object

A set of radio buttons on an HTML form. A set of radio buttons lets the user choose one item from a list.

Syntax

To define a set of radio buttons, use standard HTML syntax with the addition of the onClick event handler:

<INPUT
   TYPE="radio"
   NAME="radioName"
   VALUE="buttonValue"
   [CHECKED]
   [onClick="handlerText"]>
   textToDisplay

NAME="radioName" specifies the name of the radio object. All radio buttons in a group have the same NAME attribute. You can access this value using the name property.

VALUE="buttonValue" specifies a value that is returned to the server when the radio button is selected and the form is submitted. This defaults to "on". You can access this value using the value property.

CHECKED specifies that the radio button is selected. You can access this value using the defaultChecked property.

textToDisplay specifies the label to display beside the radio button.

Description

A radio object is a form element and must be defined within a <FORM> tag. All radio buttons in a radio button group use the same name property. To access the individual radio buttons in your code, follow the object name with an index starting from zero, one for each button the same way you would for an array such as forms: document.forms[0].radioName[0] is the first, document.forms[0].radioName[1] is the second, etc.


random method

Returns a pseudo-random number between zero and one. This method is available on Unix platforms only.

Syntax

Math.random()

Eamples

//Displays a random number between 0 and 1
document.write("The random number is " + Math.random())


referrer property

Specifies the URL of the calling document when a user clicks a link.

Syntax

document.referrer

Description

When a user navigates to a destination document by clicking a link object on a source document, the referrer property contains the URL of the source document. Evaluate the referrer property from the destination document. referrer is a read-only property.

Examples

In the following example, the getReferrer() function is called from the destination document. It returns the URL of the source document.

function getReferrer() {
   return document.referrer
}


reset object

A reset button on an HTML form. A reset button resets all elements in a form to their defaults.

Syntax

To define a reset button, use standard HTML syntax with the addition of the onClick event handler:

<INPUT
   TYPE="reset"
   NAME="resetName"
   VALUE="buttonText"
   [onClick="handlerText"]>

NAME="resetName" specifies the name of the reset object. You can access this value using the name property.

VALUE="buttonText" specifies the text to display on the button face. You can access this value using the value property.

Description

A reset object is a form element and must be defined within a <FORM> tag. The reset button's onClick event handler cannot prevent a form from being reset; once the button is clicked, the reset cannot be canceled.


round method

Returns the value of a number rounded to the nearest integer.

Syntax

Math.round(number)

number is any numeric expression or a property of an existing object.

Description

If the fractional portion of number is .5 or greater, the argument is rounded to the next highest integer. If the fractional portion of number is less than .5, the argument is rounded to the next lowest integer.

Examples

//Displays the value 20
document.write("The rounded value is " + Math.round(20.49))

//Displays the value 21
document.write("<P>The rounded value is " + Math.round(20.5))

//Displays the value -20
document.write("<P>The rounded value is " + Math.round(-20.5))

//Displays the value -21
document.write("<P>The rounded value is " + Math.round(-20.51))


search property

A string beginning with a question mark that specifies any query information in the URL.

Syntax

1. links[index].search
2. location.search

index is an integer representing a link object.

Description

The search property specifies a portion of the URL. You can set the search property at any time, although it is safer to set the href property to change a location. If the search that you specify cannot be found in the current location, you will get an error. See Section 3.3 of RFC for complete information about the search.


select method

Selects the input area of the specified password, text, or textarea object.

Syntax

1. passwordName.select()
2. textName.select()
3. textareaName.select()

passwordName is either the value of the NAME attribute of a password object or an element in the elements array.

textName is either the value of the NAME attribute of a text object or an element in the elements array. textareaName is either the value of the NAME attribute of a textarea object or an element in the elements array.

Description

Use the select method to highlight the input area of a form element. You can use the select method with the focus method to highlight a field and position the cursor for a user response.

Examples

In the following example, the checkPassword function confirms that a user has entered a valid password. If the password is not valid, the select method highlights the password field and the focus method returns focus to it so the user can re-enter the password.

function checkPassword(userPass) {
   if (badPassword) {
      alert("Please enter your password again.")
      userPass.focus()
      userPass.select()
   }
}

This example assumes that the password is defined as:

<INPUT TYPE="password" NAME="userPass">


select object (options array)

A selection list or scrolling list on an HTML form. A selection list lets the user choose one item from a list. A scrolling list lets the user choose one or more items from a list.

Syntax

To define a select object, use standard HTML syntax with the addition of the onBlur, onChange, and onFocus event handlers:

<SELECT
   NAME="selectName"
   [SIZE="integer"]
   [MULTIPLE]
   [onBlur="handlerText"]
   [onChange="handlerText"]
   [onFocus="handlerText"]>
   <OPTION VALUE="optionValue" [SELECTED]> textToDisplay [ ... <OPTION> textToDisplay]
</SELECT>

Description

A select object is a form element and must be defined within a <FORM> tag.

In JavaScript 1.1, you can now change the text of options in a Select object, and you can create options using the new Option() constructor.

The options array

You can reference the options of a select object in your code by using the options array. This array contains an entry for each option in a select object (<OPTION> tag) in source order. For example, if a select object named musicStyle contains three options, these options are reflected as musicStyle.options[0], musicStyle.options[1], and musicStyle.options[2].


selected property

A Boolean value specifying the current selection state of an option in a select object.

Syntax

selectName.options[index].selected

selectName is either the value of the NAME attribute of a select object or an element in the elements array. index is an integer representing an option in a select object.

Description

If an option in a select object is selected, the value of its selected property is true; otherwise, it is false. You can set the selected property at any time. The display of the select object updates immediately when you set the selected property. In general, the selected property is more useful than the selectedIndex property for select objects that are created with the MULTIPLE attribute. With the selected property, you can evaluate every option in the options array to determine multiple selections, and you can select individual options without clearing the selection of other options.


selectedIndex property

An integer specifying the index of the selected option in a select object.

Syntax

1. selectName.selectedIndex
2. selectName.options.selectedIndex

selectName is either the value of the NAME attribute of a select object or an element in the elements array.

select

Description

Options in a select object are indexed in the order in which they are defined, starting with an index of 0. You can set the selectedIndex property at any time. The display of the select object updates immediately when you set the selectedIndex property. Both forms of the syntax specify the same value. In general, the selectedIndex property is more useful for select objects that are created without the MULTIPLE attribute. If you evaluate selectedIndex when multiple options are selected, the selectedIndex property specifies the index of the first option only. Setting selectedIndex clears any other options that are selected in the select object. The selected property of the select object's options array is more useful for select objects that are created with the MULTIPLE attribute. With the selected property, you can evaluate every option in the options array to determine multiple selections, and you can select individual options without clearing the selection of other options.

Examples

In the following example, the getSelectedIndex() function returns the selected index in the musicType select object:

function getSelectedIndex() {
   return document.musicForm.musicType.selectedIndex
}

The previous example assumes that the select object is similar to the following:

<SELECT NAME="musicType">
   <OPTION SELECTED> R&B
   <OPTION> Jazz
   <OPTION> Blues
   <OPTION> New Age
</SELECT>


self property

The self property is a synonym for the current window or frame.

Syntax

1. self.propertyName
2. self.methodName

propertyName is the defaultStatus, status, length, or name property when self refers to a window object. propertyName is the length or name property when self refers to a frame object.

methodName is any method associated with the window object.

frame, window

Description

The self property refers to the current window or frame. Use the self property to disambiguate a window property from a form or form element of the same name. You can also use the self property to make your code more readable. The self property is read-only. The value of the self property is

     <object nameAttribute>

where nameAttribute is the NAME attribute if self refers to a frame, or an internal reference if self refers to a window.


setDate method

Sets the day of the month for a specified date.

Syntax

dateObjectName.setDate(dayValue)

dateObjectName is either the name of a date object or a property of an existing object.

dayValue is an integer from 1 to 31 or a property of an existing object, representing the day of the month.

Examples

The second statement below changes the day for theBigDay to the 24th of July from its original value.

theBigDay = new Date("July 27, 1962 23:30:00")
theBigDay.setDate(24)


setHours method

Sets the hours for a specified date.

Syntax

dateObjectName.setHours(hoursValue)

dateObjectName is either the name of a date object or a property of an existing object.

hoursValue is an integer between 0 and 23 or a property of an existing object, representing the hour.

Examples

theBigDay.setHours(7)


setMinutes method

Sets the minutes for a specified date.

Syntax

dateObjectName.setMinutes(minutesValue)

dateObjectName is either the name of a date object or a property of an existing object.

minutesValue is an integer between 0 and 59 or a property of an existing object, representing the minutes.

Examples

theBigDay.setMinutes(45)


setMonth method

Sets the month for a specified date.

Syntax

dateObjectName.setMonth(monthValue)

dateObjectName is either the name of a date object or a property of an existing object.

monthValue is an integer between 0 and 11 (representing the months January through December), or a property of an existing object.

Examples

theBigDay.setMonth(6)


setSeconds method

Sets the seconds for a specified date.

Syntax

dateObjectName.setSeconds(secondsValue)

dateObjectName is either the name of a date object or a property of an existing object.

secondsValue is an integer between 0 and 59 or a property of an existing object.

Examples

theBigDay.setSeconds(30)


setTime method

Sets the value of a date object.

Syntax

dateObjectName.setTime(timevalue)

dateObjectName is either the name of a date object or a property of an existing object.

timevalue is an integer or a property of an existing object, representing the number of milliseconds since the epoch (1 January 1970 00:00:00).

Description

Use the setTime method to help assign a date and time to another date object.

Examples

theBigDay = new Date("July 1, 1999")
sameAsBigDay = new Date()
sameAsBigDay.setTime(theBigDay.getTime())


setTimeout method

Evaluates an expression after a specified number of milliseconds have elapsed.

Syntax

timeoutID=setTimeout(expression, msec)

timeoutID is an identifier that is used only to cancel the evaluation with the clearTimeout method. expression is a string expression or a property of an existing object.

msec is a numeric value, numeric string, or a property of an existing object in millisecond units.

Description

The setTimeout method evaluates an expression after a specified amount of time. It does not evaluate the expression repeatedly. For example, if a setTimeout method specifies 5 seconds, the expression is evaluated after 5 seconds, not every 5 seconds.


setYear method

Sets the year for a specified date.

Syntax

dateObjectName.setYear(yearValue)

dateObjectName is either the name of a date object or a property of an existing object.

yearValue is an integer greater than 1900 or a property of an existing object.

Examples

theBigDay.setYear(96)


sin method

Returns the sine of a number.

Syntax

Math.sin(number)

number is a numeric expression or a property of an existing object, representing the size of an angle in radians.

Description

The sin method returns a numeric value between -1 and 1, which represents the sine of the angle.

Examples

//Displays the value 1
document.write("The sine of pi/2 radians is " +
   Math.sin(Math.PI/2))

//Displays the value 1.224606353822377e-016
document.write("<P>The sine of pi radians is " +
   Math.sin(Math.PI))

//Displays the value 0
document.write("<P>The sine of 0 radians is " +
   Math.sin(0))


small method

Causes a string to be displayed in a small font as if it were in a <SMALL> tag.

Syntax

stringName.small()

stringName is any string or a property of an existing object.

Description

Use the small method with the write or writeln methods to format and display a string in a document.

Examples

The following example uses string methods to change the size of a string:

var worldString="Hello, world"
document.write(worldString.small())
document.write("<P>" + worldString.big())
document.write("<P>" + worldString.fontsize(7))

The previous example produces the same output as the following HTML:

<SMALL>Hello, world</SMALL>
<P><BIG>Hello, world</BIG>
<P><FONTSIZE=7>Hello, world</FONTSIZE>


sqrt method

Returns the square root of a number.

Syntax

Math.sqrt(number)

number is any non-negative numeric expression or a property of an existing object.

Description

If the value of number is outside the suggested range, the return value is always 0.

Examples

//Displays the value 3
document.write("The square root of 9 is " + Math.sqrt(9))

//Displays the value 1.414213562373095
document.write("<P>The square root of 2 is " + Math.sqrt(2))

//Displays the value 0 because the argument is out of range
document.write("<P>The square root of -1 is " + Math.sqrt(-1))


SQRT1_2 property

The square root of one-half; equivalently, one over the square root of two, approximately 0.707.

Syntax

Math.SQRT1_2

Description

Because SQRT1_2 is a constant, it is a read-only property of Math.

Examples

The following example displays 1 over the square root of 2:

document.write("1 over the square root of 2 is " + Math.SQRT1_2)


SQRT2 property

The square root of two, approximately 1.414.

Syntax

Math.SQRT2

Description

Because SQRT2 is a constant, it is a read-only property of Math.

Examples

The following example displays the square root of 2:

document.write("The square root of 2 is " + Math.SQRT2)


status property

Specifies a priority or transient message in the status bar at the bottom of the window, such as the message that appears when a mouseOver event occurs over an anchor.

Syntax

windowReference.status

windowReference is a valid way of referring to a window, as described in the window object.

Description

Do not confuse the status property with the defaultStatus property. The defaultStatus property reflects the default message displayed in the status bar. You can set the status property at any time. You must return true if you want to set the status property in the onMouseOver event handler.


strike method

Causes a string to be displayed as struck out text as if it were in a <STRIKE> tag.

Syntax

stringName.strike()

stringName is any string or a property of an existing object.

Description

Use the strike method with the write or writeln methods to format and display a string in a document.

Examples

The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"

document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())

The previous example produces the same output as the following HTML:

<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>


link, bold, italics methods
blink, bold, italics methods


string object

A series of characters.

In JavaScript 1.1, String objects are now "real" objects. In previous releases, you constructed strings by quoting some characters, and if you wanted to use the string as an object, you followed the string reference with a property or method name such as .length or .indexOf("sub"). Now you can create String objects using the String() constructor.

Syntax

To use a string object:

1. stringName.propertyName
2. stringName.methodName(parameters)
stringName is the name of a string variable. propertyName is one of the properties listed below. methodName is one of the methods listed below.

Description

The string object is a built-in JavaScript object. A string can be represented as a literal enclosed by single or double quotes; for example, "Netscape" or 'Netscape'.

Additionally, in JavaScript 1.1, Strings can now be passed among scripts in different windows or frames.


sub method

Causes a string to be displayed as a subscript as if it were in a <SUB> tag.

Syntax

stringName.sub()

stringName is any string or a property of an existing object.

Description

Use the sub method with the write or writeln methods to format and display a string in a document.

Examples

The following example uses the sub and sup methods to format a string:

var superText="superscript"
var subText="subscript"

document.write("This is what a " + superText.sup() + " looks like.")
document.write("<P>This is what a " + subText.sub() + " looks like.")

The previous example produces the same output as the following HTML:

This is what a <SUP>superscript</SUP> looks like.
<P>This is what a <SUB>subscript</SUB> looks like.


submit method

Submits a form.

Syntax

formName.submit()

formName is the name of any form or an element in the forms array.

Description

The submit method submits the specified form. It performs the same action as a submit button. Use the submit method to send data back to an http server. The submit method returns the data using either "get" or "post", as specified in the method property.

Examples

The following example submits a form called musicChoice:

document.musicChoice.submit()

If musicChoice is the first form created, you also can submit it as follows:

document.forms[0].submit()


submit object

A submit button on an HTML form. A submit button causes a form to be submitted.

Syntax

To define a submit button, use standard HTML syntax with the addition of the onClick event handler:

<INPUT
   TYPE="submit"
   NAME="submitName"
   VALUE="buttonText"
   [onClick="handlerText"]>

NAME="submitName" specifies the name of the submit object. You can access this value using the name property.

VALUE="buttonText" specifies the label to display on the button face. You can access this value using the value property.

Description

A submit object is a form element and must be defined within a <FORM> tag.


substring method

Returns a subset of a string object.

Syntax

stringName.substring(indexA, indexB)

stringName is any string or a property of an existing object.

indexA is any integer from 0 to stringName.length - 1, or a property of an existing object.

indexB is any integer from 0 to stringName.length - 1, or a property of an existing object.

Description

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character is stringName.length - 1. If indexA is less than indexB, the substring method returns the subset starting with the character at indexA and ending with the character before indexB. If indexA is greater than indexB, the substring method returns the subset starting with the character at indexB and ending with the character before indexA. If indexA is equal to indexB, the substring method returns the empty string.

Examples

The following example uses substring to display characters from the string "Netscape".

var anyString="Netscape"

//Displays "Net"
document.write(anyString.substring(0,3))
document.write(anyString.substring(3,0))
//Displays "cap"
document.write(anyString.substring(4,7))
document.write(anyString.substring(7,4))


sup method

Causes a string to be displayed as a superscript as if it were in a <SUP> tag.

Syntax

stringName.sup()

stringName is any string or a property of an existing object.

Description

Use the sup method with the write or writeln methods to format and display a string in a document.

Examples

The following example uses the sub and sup methods to format a string:

var superText="superscript"
var subText="subscript"
document.write("This is what a " + superText.sup() + " looks like.")
document.write("<P>This is what a " + subText.sub() + " looks like.")

The previous example produces the same output as the following HTML:

This is what a <SUP>superscript</SUP> looks like.
<P>This is what a <SUB>subscript</SUB> looks like.


tan method

Returns the tangent of a number.

Syntax

Math.tan(number)

number is a numeric expression representing the size of an angle in radians, or a property of an existing object.

Description

The tan method returns a numeric value which represents the tangent of the angle.

Examples

//Displays the value 0.9999999999999999
document.write("The tangent of pi/4 radians is " +
   Math.tan(Math.PI/4))

//Displays the value 0
document.write("<P>The tangent of 0 radians is " +
   Math.tan(0))


target property

For form, a string specifying the name of the window that responses go to after a form has been submitted. For link, a string specifying the name of the window that displays the content of a clicked hypertext link.

Syntax

1. formName.target
2. links[index].target

formName is either the name of a form or an element in the forms array.

index is an integer representing a link object.

Description

The target property initially reflects the TARGET attribute of the <FORM> and <A> tags; however, setting target overrides these attributes. The target property cannot be assigned the value of a JavaScript expression or variable. You can set the target property at any time. Certain values of the target property may require specific values for other form properties. See RFC for more information.

Examples

The following example specifies that responses to the musicInfo form are displayed in the "msgWindow" window:

document.musicInfo.target="msgWindow"


text object

A text input field on an HTML form. A text field lets the user enter a word, phrase, or series of numbers.

Syntax

To define a text object, use standard HTML syntax with the addition of the onBlur, on Change, onFocus, and onSelect event handlers:

<INPUT
   TYPE="text"
   NAME="textName"
   VALUE="textValue"
   SIZE=integer
   [onBlur="handlerText"]
   [onChange="handlerText"]
   [onFocus="handlerText"]
   [onSelect="handlerText"]>

NAME="textName" specifies the name of the text object. You can access this value using the name property.

VALUE="textValue" specifies the initial value of the text object. You can access this value using the defaultValue property.

SIZE=integer specifies the number of characters the text object can accommodate without scrolling.

Description

A text object is a form element and must be defined within a <FORM> tag.


text property

A string specifying the text that follows an <OPTION> tag in a select object.

Syntax

selectName.options[index].text

selectName is either the value of the NAME attribute of a select object or an element in the elements array. index is an integer representing an option in a select object.

Description

The text property initially reflects the text that follows an <OPTION> tag in a select object. You can set the text property at any time; however, the following effects result:

The value of the property changes.

The text displayed by the option in the select object does not change. Be careful if you change the text property. If you evaluate the property after you change it, the property contains the new value, not the value that is displayed onscreen.

Examples

In the following example, the getChoice() function returns the value of the text property for the selected option. The for loop evaluates every option in the musicType select object. The if statement finds the option that is selected.

function getChoice() {
   for (var i = 0; i  document.musicForm.musicType.length; i++) {
      if (document.musicForm.musicType.options[i].selected == true) {
         return document.musicForm.musicType.options[i].text
      }
   }
   return null
}


textarea object

A multiline input field on an HTML form. A textarea field lets the user enter words, phrases, or numbers.

Syntax

To define a text area, use standard HTML syntax with the addition of the onBlur, onChange, onFocus, and onSelect event handlers:

<TEXTAREA
   NAME="textareaName"
   ROWS="integer"
   COLS="integer"
   WRAP="off|virtual|physical"
   [onBlur="handlerText"]
   [onChange="handlerText"]
   [onFocus="handlerText"]
   [onSelect="handlerText"]>
   textToDisplay
</TEXTAREA>

NAME="textareaName" specifies the name of the textarea object. You can access this value using the name property.

ROWS="integer" and COLS="integer" define the physical size of the displayed input field in numbers of characters.

textToDisplay specifies the initial value of the textarea object. A textarea allows only ASCII text, and new lines are respected. You can access this value using the defaultValue property.

The WRAP attribute controls word wrapping inside the TEXTAREA. The value "off" is default and lines are sent exactly as typed. The value "virtual" wraps in the display but are sent exactly as typed. The value "physical" wraps in the display and sends new-lines at the wrap points as if new-lines had been entered.

Description

A textarea object is a form element and must be defined within a <FORM> tag.


title property

A string representing the title of a document.

Syntax

document.title

Description

The title property is a reflection of the value specified within the <TITLE> and </TITLE> tags. If a document does not have a title, the title property is null. title is a read-only property.

Examples

In the following example, the value of the title property is assigned to a variable called docTitle:

var newWindow = window.open("http://www.netscape.com")
var docTitle = newWindow.document.title


toGMTString method

Converts a date to a string, using the Internet GMT conventions.

Syntax

dateObjectName.toGMTString()

dateObjectName is either the name of a date object or a property of an existing object.

Description

The exact format of the value returned by toGMTString varies according to the platform.

Examples

In the following example, today is a date object:

today.toGMTString()


toLocaleString method

Converts a date to a string, using the current locale's conventions.

Syntax

dateObjectName.toLocaleString()

dateObjectName is either the name of a date object or a property of an existing object.

Description

If you are trying to pass a date using toLocaleString, be aware that different locales assemble the string in different ways. Using methods such as getHours, getMinutes, and getSeconds will give more portable results.

Examples

In the following example, today is a date object:

today.toLocaleString()

In this example, toLocaleString returns a string value that is similar to the following form. The exact format depends on the platform.12/18/95 17:28:35


toLowerCase method

Returns the calling string value converted to lower case.

Syntax

stringName.toLowerCase()

stringName is any string or a property of an existing object.

Description

The toLowerCase method returns the value of stringName converted to lower case. toLowerCase does not affect the value of stringName itself.

Examples

The following examples both yield "alphabet".

var upperText="ALPHABET"
document.write(upperText.toLowerCase())

"ALPHABET".toLowerCase()


top property

The top property is a synonym for the top-most Navigator window, which is a "document window" or "Web Browser window."

Description

The top property refers to the top-most window that contains frames or nested framesets. Use the top property to refer to this ancestor window. The top property is read-only. The value of the top property is

     <object objectReference>

where objectReference is an internal reference.

Examples

The statement top.close() closes the top-most ancestor window. The statement top.length specifies the number of frames contained within the top-most ancestor window. When the top-most ancestor is defined as follows, top.length returns 3:

<FRAMESET COLS="30%,40%,30%">
<FRAME SRC=child1.htm NAME="childFrame1">
<FRAME SRC=child2.htm NAME="childFrame2">
<FRAME SRC=child3.htm NAME="childFrame3">
</FRAMESET>

The following example sets the background color of a frame called myFrame to red. myFrame is a child of the top-most ancestor window.

top.myFrame.document.bgColor="red"


toUpperCase method

Returns the calling string value converted to upper case.

Syntax

stringName.toUpperCase()

stringName is any string or a property of an existing object.

Description

The toUpperCase method returns the value of stringName converted to upper case. toUpperCase does not affect the value of stringName itself.

Examples

The following examples both yield "ALPHABET".

var lowerText="alphabet"
document.write(lowerText.toUpperCase())

"alphabet".toUpperCase()


unescape function

Returns the ASCII string for the specified value.

Syntax

unescape("string")

string is a string or a property of an existing object, containing characters in either of the following forms:

"%integer", where integer is a number between 0 and 255 (decimal)

"hex", where hex is a number between 0x0 and 0xFF (hexadecimal)

Description

The unescape function is not a method associated with any object, but is part of the language itself. The string returned by the unescape function is a series of characters in the ISO Latin-1 character set.

Examples

The following example returns "&"

unescape("%26")

The following example returns "!#"

unescape("%21%23")


userAgent property

A string representing the value of the user-agent header sent in the HTTP protocol from client to server.

Syntax

navigator.userAgent

Description

Servers use the value sent in the user-agent header to identify the client. userAgent is a read-only property.

Examples

The following example displays userAgent information for the Navigator:

document.write("The value of navigator.userAgent is " +
   navigator.userAgent)

For Navigator 2.0, this displays the following:

The value of navigator.userAgent is Mozilla/2.0 (Win16; I)


UTC method

Returns the number of milliseconds in a date object since January 1, 1970 00:00:00, Universal Coordinated Time (GMT).

Syntax

Date.UTC(year, month, day [, hrs] [, min] [, sec])

year is a year after 1900. month is a month between 0-11.

date is a day of the month between 1-31.

hrs is hours between 0-23.

min is minutes between 0-59.

sec is seconds between 0-59.

Description

UTC takes comma-delimited date parameters and returns the number of milliseconds since January 1, 1970 00:00:00, Universal Coordinated Time (GMT). Because UTC is a static method of Date, you always use it as Date.UTC(), rather than as a method of a date object you created.

Examples

The following statement creates a date object using GMT instead of local time:

gmtDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0))


value property

A string that is related to the VALUE attribute of its object.


vlinkColor property

A string specifying the color of visited links.

Syntax

document.vlinkColor

Description

The vlinkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in Color. This property is the JavaScript reflection of the VLINK attribute of the <BODY> tag. The default value of this property is set by the user on the Colors tab of the Preferences dialog box, which is displayed by choosing General Preferences from the Options menu. You cannot set this property after the HTML source has been through layout. If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".

Examples

The following example sets the color of visited links to aqua using a string literal:

document.vlinkColor="aqua"

The following example sets the color of active links to aqua using a hexadecimal triplet:

document.vlinkColor="00FFFF"


window object

The top-level object for each document, location, and history object group.

Syntax

To define a window, use the open method:

windowVar = window.open("URL", "windowName" [,"windowFeatures"])

Description

The window object is the top-level object in the JavaScript client hierarchy. Frame objects are also windows. The self and window properties are synonyms for the current window, and you can optionally use them to refer to the current window. For example, you can close the current window by calling either window.close() or self.close(). You can use these properties to make your code more readable, or to disambiguate the property reference self.status from a form called status.


window property

The window property is a synonym for the current window or frame.

Syntax

1. window.propertyName
2. window.methodName

propertyName is the defaultStatus, status, length, or name property when the calling window refers to a window object. propertyName is the length or name property when the calling window refers to a frame object.

methodName is any method associated with the window object.

Description

The window property refers to the current window or frame. Although you can use the window property as a synonym for the current frame, your code is more readable if you use the self property. For example, window.name and self.name both specify the name of the current frame, but self.name is easier to understand. Use the window property to disambiguate a property of the window object from a form or form element of the same name. You can also use the window property to make your code more readable. The window property is read-only. The value of the window property is

     <object nameAttribute>

where nameAttribute is the NAME attribute if window refers to a frame, or an internal reference if window refers to a window.


write method

Writes one or more HTML expressions to a document in the specified window.

Syntax

document.write(expression1 [,expression2], ...[,expressionN])

expression1 through expressionN are any JavaScript expressions or the properties of existing objects.

Description

The write method displays any number of expressions in a document window. You can specify any JavaScript expression with the write method, including numerics, strings, or logicals. The write method is the same as the writeln method, except the write method does not append a newline character to the end of the output. Use the write method within any <SCRIPT> tag or within an event handler. Event handlers execute after the original document closes, so the write method will implicitly open a new document of mimeType text/html if you do not explicitly issue a document.open() method in the event handler.

Examples

In the following example, the write method takes several arguments, including strings, a numeric, and a variable:

var mystery = "world"
// Displays Hello world testing 123
msgWindow.document.write("Hello ", mystery, " testing ", 123)


writeln method

Writes one or more HTML expressions to a document in the specified window and follows them with a newline character.

Syntax

document.writeln(expression1 [,expression2], ...[,expressionN])

expression1 through expressionN are any JavaScript expressions or the properties of existing objects.

Description

The writeln method displays any number of expressions in a document window. You can specify any JavaScript expression, including numerics, strings, or logicals. The writeln method is the same as the write method, except the writeln method appends a newline character to the end of the output. HTML ignores the newline character, except within certain tags such as <PRE>. Use the writeln method within any <SCRIPT> tag or within an event handler. Event handlers execute after the original document closes, so the writeln method will implicitly open a new document of mimeType text/html if you do not explicitly issue a document.open() method in the event handler.


break

A statement that terminates the current while or for loop and transfers program control to the statement following the terminated loop.

Syntax

break

Examples

The following function has a break statement that terminates the while loop when i is 3, and then returns the value 3 * x.

function testBreak(x) {

   var i = 0

   while (i < 6) {

      if (i == 3)

         break

      i++

   }

   return i*x

}


comment

Notations by the author to explain what a script does. Comments are ignored by the interpreter. JavaScript supports Java-style comments:

Comments on a single line are preceded by a double-slash (//).

Comments that span multiple lines are preceded by a /* and followed by a */.

Syntax

1. // comment text
2. /* multiple line comment text */

Examples

// This is a single-line comment.

/* This is a multiple-line comment.

   It can be of any length,

   and you can put whatever you want here. */


continue

A statement that terminates execution of the block of statements in a while or for loop, and continues execution of the loop with the next iteration. In contrast to the break statement, continue does not terminate the execution of the loop entirely: instead,

In a while loop, it jumps back to the condition.

In a for loop, it jumps to the update expression.

Syntax

continue

Examples

The following example shows a while loop that has a continue statement that executes when the value of i is 3. Thus, n takes on the values 1, 3, 7, and 12.

i = 0

n = 0

while (i < 5) {

   i++

   if (i == 3)

      continue

   n += i

}


for

A statement that creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a block of statements executed in the loop.

Syntax

for ([initial-expression;] [condition;] [increment-expression]) {
   statements
}

initial-expression is a statement or variable declaration. It is typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword.

condition is evaluated on each pass through the loop. If this condition evaluates to true, the statements in statements are performed. This conditional test is optional. If omitted, the condition always evaluates to true.

increment-expression is generally used to update or increment the counter variable.

statements is a block of statements that are executed as long as condition evaluates to true. This can be a single statement or multiple statements. Although not required, it is good practice to indent these statements from the beginning of the for statement.

Examples

The following for statement starts by declaring the variable i and initializing it to zero. It checks that i is less than nine, performs the two succeeding statements, and increments i by one after each pass through the loop.

for (var i = 0; i < 9; i++) {

   n += i

   myfunc(n)

}


for...in

A statement that iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements.

Syntax

for (variable in object) {
   statements }

variable is the variable to iterate over every property.

object is the object for which the properties are iterated.

statements specifies the statements to execute for each property.

Examples

The following function takes as its argument an object and the object's name. It then iterates over all the object's properties and returns a string that lists the property names and their values.

function dump_props(obj, obj_name) {

   var result = ""

   for (var i in obj) {

      result += obj_name + "." + i + " = " + obj[i] + "<BR>"

   }

   result += "<HR>"

   return result

}


function

A statement that declares a JavaScript function name with the specified parameters param. Acceptable parameters include strings, numbers, and objects.

To return a value, the function must have a return statement that specifies the value to return. You cannot nest a function statement in another statement or in itself.

All parameters are passed to functions, by value. In other words, the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.

Syntax

function name([param] [, param] [..., param]) {
   statements }

Examples

//This function returns the total dollar amount of sales, when

//given the number of units sold of products a, b, and c.

function calc_sales(units_a, units_b, units_c) {

   return units_a*79 + units_b*129 + units_c*699

}


if...else

A statement that executes a set of statements if a specified condition is true. If the condition is false, another set of statements can be executed.

Syntax

if (condition) {
   statements1 }
[else {
   statements2}]

condition can be any JavaScript expression that evaluates to true or false. Parentheses are required around the condition. If condition evaluates to true, the statements in statements1 are executed.

statements1 and statements2 can be any JavaScript statements, including further nested if statements. Multiple statements must be enclosed in braces.

Examples

if ( cipher_char == from_char ) {

   result = result + to_char

   x++ }

else

   result = result + clear_char


new

An operator that lets you create an instance of a user-defined object type.

Creating an object type requires two steps:

Define the object type by writing a function.

Create an instance of the object with new.

To define an object type, create a function for the object type that specifies its name, properties, and methods. An object can have a property that is itself another object. See the examples below.

You can always add a property to a previously defined object. For example, the statement car1.color = "black" adds a property color to car1, and assigns it a value of "black". However, this does not affect any other objects. To add the new property to all objects of the same type, you must add the property to the definition of the car object type.

Syntax

objectName = new objectType ( param1 [,param2] ...[,paramN] )

objectName is the name of the new object instance.

objectType is the object type. It must be a function that defines an object type.

param1...paramN are the property values for the object. These properties are parameters defined for the objectType function.


return

A statement that specifies the value to be returned by a function.

Syntax

return expression

Examples

The following function returns the square of its argument, x, where x is a number.

function square( x ) {

   return x * x

}


this

A keyword that you can use to refer to the current object. In general, in a method this refers to the calling object.

Syntax

this[.propertyName]

Examples

Suppose a function called validate validates an object's value property, given the object and the high and low values:

function validate(obj, lowval, hival) {

   if ((obj.value < lowval) || (obj.value > hival))

      alert("Invalid Value!")

}

You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

<B>Enter a number between 18 and 99:</B>

<INPUT TYPE = "text" NAME = "age" SIZE = 3

   onChange="validate(this, 18, 99)">


var

A statement that declares a variable, optionally initializing it to a value. The scope of a variable is the current function or, for variables declared outside a function, the current application.

Using var outside a function is optional; you can declare a variable by simply assigning it a value. However, it is good style to use var, and it is necessary in functions if a global variable of the same name exists.

Syntax

var varname [= value] [..., varname [= value] ]

varname is the variable name. It can be any legal identifier. value is the intial value of the variable and can be any legal expression.

Examples

 var num_hits = 0, cust_no = 0


while

A statement that creates a loop that evaluates an expression, and if it is true, executes a block of statements. The loop then repeats, as long as the specified condition is true.

Syntax

while (condition) {
   statements
}

condition is evaluated before each pass through the loop. If this condition evaluates to true, the statements in the succeeding block are performed. When condition evaluates to false, execution continues with the statement following statements.

statements is a block of statements that are executed as long as the condition evaluates to true. Although not required, it is good practice to indent these statements from the beginning of the while statement.

Examples

The following while loop iterates as long as n is less than three.

n = 0

x = 0

while( n < 3 ) {

   n ++

   x += n

}

Each iteration, the loop increments n and adds it to x. Therefore, x and n take on the following values:

After the first pass: n = 1 and x = 1

After the second pass: n = 2 and x = 3

After the third pass: n = 3 and x = 6

After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.


with

A statement that establishes a the default object for a set of statements. Within the set of statements, any property references that do not specify an object are assumed to be for the default object.

Syntax

with (object){
    statements
}

object specifies the default object to use for the statements. The parentheses are required around object. statements is any block of statements.

Examples

The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references.

var a, x, y

var r=10

with (Math) {

   a = PI * r * r

   x = r * cos(PI)

   y = r * sin(PI/2)

}


Reserved Word

A reserved word cannot be used as a JavaScript variable, function, method, or object name. Some reserved words are keywords used in JavaScript; others are reserved for future use.


applet object

(JavaScript 1.1)

Includes a Java applet in a web page.

HTML syntax

<APPLET
   CODE=classFileName
   HEIGHT=height
   WIDTH=width
   MAYSCRIPT
   [NAME=appletName]
   [CODEBASE=classFileDirectory]
   [ALT=alternateText]
   [ALIGN="left"|"right"|
      "top"|"absmiddle"|"absbottom"|
      "texttop"|"middle"|"baseline"|"bottom"]
   [HSPACE=spaceInPixels]
   [VSPACE=spaceInPixels]>
   [<PARAM NAME=parameterName VALUE=parameterValue>]
   [ ... <PARAM>]
</APPLET>

Description

The author of an HTML page must permit an applet to access JavaScript by specifying the MAYSCRIPT attribute of the APPLET tag. This prevents an applet from accessing JavaScript on a page without the knowledge of the page author.

The applets array

You can reference the applets in your code by using the applets array. This array contains an entry for each Applet object (<APPLET> tag) in a document in source order. For example, if a document contains three applets, these applets are reflected as document.applets[0], document.applets[1], and document.applets[2].


area object

(JavaScript 1.1)
Defines an area of an image as an image map. When the user clicks the area, the area's hypertext reference is loaded into its target window.

HTML syntax

To define an area, use standard HTML syntax with the addition of the onMouseOut and onMouseOver event handlers:

<MAP NAME="mapName">
   <AREA
      [NAME="areaName"]
      COORDS="x1,y1,x2,y2,..."|"x-center,y-center,radius"
      HREF="location"
      [SHAPE="rect"|"poly"|"circle"|"default"]
      [TARGET="windowName"]
      [onMouseOut="handlerText"]
      [onMouseOver="handlerText"]>
</MAP>

Description

Area objects are in the links array. You cannot refer to an Area object by name; you must use the links array. For example, if a document contains three area objects, these objects are reflected as document.links[0], document.links[1], and document.links[2].

The HREF attribute is required for Area objects that use the onMouseOut or onMouseOver event handlers. However, if you create an Area for an image and do not want the image to link to a hypertext reference when clicked, specify a JavaScript function in the area's HREF attribute by using the javascript: URL protocol.


arguments property

The arguments property is now a property of the Function object.

Syntax

To specify the arguments array from within a Function object:

this.arguments[index]


Array object

(JavaScript 1.1)
Lets you create arrays and work with them.

Syntax

To create an Array object:

1. arrayObjectName = new Array()
2. arrayObjectName = new Array(arrayLength)

Description

The Array object is a built-in JavaScript object.

Examples

The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100.

msgArray = new Array()

msgArray [0] = "Hello"

msgArray [99] = "world"

if (msgArray .length == 100)
// This is true, because defined msgArray [99] element.

document.write("The length is 100.")


atan2 method

(JavaScript 1.1)
Returns the angle (theta component) of the polar coordinate (r,theta) that corresponds to the specified cartesian coordinate (x,y).

Syntax

Math.atan2(x,y)

x is either a numeric expression or a property of an existing object, representing the cartesian x-coordinate.
y is either a numeric expression or a property of an existing object, representing the cartesian y-coordinate.

Description

The atan2 method returns a numeric value.

Examples

The following function returns the angle of the polar coordinate:

function getAtan2(x,y) { return Math.atan2(x,y) }

If you pass getAtan2 the values (90,15), it returns 1.4056476493802699; if you pass it the values (15,90), it returns 0.16514867741462683.


border property

(JavaScript 1.1)
A string specifying the width, in pixels, of an image border. (read-only )

Syntax

imageName.border

imageName is either the name of an Image object or an element in the images array.

Description

The border property reflects the BORDER attribute of the <IMG> tag. For images created with the Image() constructor, the value of the border property is 0.

Examples

The following function displays the value of an image's border property if the value is not zero.

function checkBorder(theImage) {

if (theImage.border==0) {

alert('The image has no border!') }

else {

alert('The image's border is ' + theImage.border)

}


complete property

(JavaScript 1.1)

A boolean value that indicates whether Navigator has completed its attempt to load an image.  (read-only )

Syntax

imageName.complete

imageName is either the name of an Image object or an element in the images array.


description property

(JavaScript 1.1)

Syntax

1. navigator.mimeTypes[index].description
2. navigator.mimeTypes[mimeTypeName].description
3. navigator.plugins[index].description
4. navigator.plugins[pluginName].description


enabledPlugin property

(JavaScript 1.1)

Returns a reference to the Plugin object for the plug-in that handles that MIME type, or NULL if no plug-in handles that MIME type.


filename property

(JavaScript 1.1)

A plug-in's file name.

Syntax

1. navigator.plugins[index].filename
2. navigator.plugins[pluginName].filename


FileUpload object

(JavaScript 1.1)
A file upload element on an HTML form. A file upload element lets the user supply a file as input.

HTML syntax

To define a FileUpload object, use standard HTML syntax:

<INPUT
   TYPE="file"
   NAME="fileUploadName">

NAME="fileUploadName" specifies the name of the FileUpload object (this is not the name of the file to upload). You can access this value using the name property.

Syntax

To use a FileUpload object's properties:

fileUploadName.propertyName

fileUploadName is the value of the NAME attribute of a FileUpload object.
propertyName is one of the properties listed below.

Description

You can place a FileUpload object on a form but you cannot use JavaScript to modify it in any way.


Function object

(JavaScript 1.1)
Specifies a string of JavaScript code to be compiled as a function.

Syntax

functionTarget = new Function ([arg1, arg2, ... argn], functionBody)

functionTarget is the name of a variable or a property of an existing object. It can also be an object followed by a lowercase event handler name, such as window.onerror.
arg1, arg2, ... argn are string arguments to be used by the function as formal argument names.
functionBody is a string specifying the JavaScript code to be compiled as the function body.

Description

Function objects are evaluated each time they are used. This is less efficient than declaring a function and calling it within your code, because declared functions are compiled.

Examples

The following code assigns a function to the variable setBGColor. This function sets the current document's background color.

 var setBGColor = new Function("document.bgColor='antiquewhite'")

To call the Function object, you can specify the variable name as if it were a function. The following code executes the function specified by the setBGColor variable:

 var colorChoice="antiquewhite"

if (colorChoice=="antiquewhite") {

setBGColor()

}


height property

(JavaScript 1.1)
A string specifying the height of an image either in pixels or as a percentage of the window height.

Syntax

imageName.height

imageName is either the name of an Image object or an element in the images array.

Description

The height property reflects the HEIGHT attribute of the <IMG> tag. For images created with the Image() constructor, the value of the height property is the actual, not the displayed, height of the image.
height is a read-only property.

Examples

The following function displays the values of an image's height, width, hspace, and vspace properties.

function showImageSize(theImage) {

alert('height=' + theImage.height+ '; width=' +

theImage.width + '; hspace=' + theImage.hspace +

'; vspace=' + theImage.vspace)

}


hspace property

(JavaScript 1.1)
A string specifying a margin in pixels between the left and right edges of an image and the surrounding text. (read-only )

Syntax

imageName.hspace

imageName is either the name of an Image object or an element in the images array.

Description

The hspace property reflects the HSPACE attribute of the <IMG> tag. For images created with the Image() constructor, the value of the hspace property is 0.
hspace is a property.


Image object (images array)

(JavaScript 1.1)
An image on an HTML form.

HTML syntax

To define an image, use standard HTML syntax with the addition of the onAbort and onLoad event handlers:

<IMG
   [NAME="imageName"]
   SRC="Location"
   [LOWSRC="Location"]
   [HEIGHT="Pixels"|"Value"%]
   [WIDTH="Pixels"|"Value"%]
   [HSPACE="Pixels"]
   [VSPACE="Pixels"]
   [BORDER="Pixels"]
   [ALIGN="left"|"right"|
      "top"|"absmiddle"|"absbottom"|
      "texttop"|"middle"|"baseline"|"bottom"]
   [ISMAP]
   [USEMAP="Location#MapName"]
   [onAbort="handlerText"]
   [onError="handlerText"]
   [onLoad="handlerText"]>

Description

The position and size of an image in a document are set when the document is displayed in Navigator and cannot be changed. You can change the image displayed by setting the src and lowsrc properties.

The Image() constructor

The primary use for an Image object created with the Image() constructor is to load an image from the network (and decode it) before it is actually needed for display. Then when you need to display the image within an existing image cell, set the src property of the displayed image to the same value as that used for the prefetched image, as follows.

myImage = new Image()

myImage.src = "seaotter.gif"

...

document.images[0].src = myImage.src

The resulting image will be obtained from cache, rather than loaded over the network. You can use this technique to create smooth animations, or you could display one of several images based on form input.


javaEnabled method

(JavaScript 1.1)
Specifies whether Java is enabled.

Syntax

navigator.javaEnabled()

Description

javaEnabled returns true if Java is enabled, false otherwise. The user can enable or disable Java by choosing Network Preferences from the Navigator's Options menu.

Examples

The following code executes function1 if Java is enabled; otherwise it executes function2.

if (navigator.javaEnabled()) {

function1() }

else function2()


join method

(JavaScript 1.1)
Joins all elements of an array into a string.

Syntax

arrayName.join(separator)

arrayName is the name of an Array object or a property of an existing object.
separator specifies a string to separate each element of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (,).

Description

The string conversion of all array elements are joined into one string.

Examples

The following example creates an array, a with three elements, then joins the array three times: using the default separator, then a comma and a space, and then a plus.

 a = new Array("Wind","Rain","Fire") document.write(a.join() +"
") document.write(a.join(", ") +"
") document.write(a.join(" + ") +"
")

 This code produces the following output:

 Wind,Rain,Fire Wind, Rain, Fire Wind + Rain + Fire


lowsrc property

(JavaScript 1.1)
A string specifying the URL of a low-resolution version of an image to be displayed in a document.

Syntax

imageName.lowsrc

imageName is either the name of an Image object or an element in the images array.

Description

The lowsrc property initially reflects the LOWSRC attribute of the <IMG> tag. Navigator loads the smaller image specified by lowsrc and then replaces it with the larger image specified by the src property. You can change the lowsrc property at any time.


mimeTypes

(JavaScript 1.1)

An array of all MIME types supported by the client.


Option object

(JavaScript 1.1)

A Select object option created using the Option() constructor.

Description

To create an option to add to an existing Select object:

optionName = new Option([optionText, optionValue, defaultSelected, selected])

To add the new option to an existing Select object:

selectName.options[index]=optionName


Plugin object (plugins array)

(JavaScript 1.1)
Generates output from a plug-in application.

Syntax

<EMBED
   SRC=source
   NAME=appletName
   HEIGHT=height
   WIDTH=width>
   [<PARAM NAME=parameterName VALUE=parameterValue>]
   [ ... <PARAM>]
</EMBED>


prototype property

(JavaScript 1.1)
Defines a property that is shared by all objects of the specified type.

Syntax

objectType.prototype.propertyName = value

objectType is the name of the constructor specifying the object type.
propertyName is the name of the property to be created.
value is the property value initially assigned for all objects of the specified objectType.

Description

Use the prototype property to explicitly add properties to objects created with the new operator.
For example, you can create Date objects by using the Date() constructor and the new operator. Date.prototype refers to the prototype object for the Date() constructor. If you set a property for the prototype, such as Date.prototype.description, then all objects created with Date() will have the description property, even if the objects already exist.

var today = new Date()

var birthday = new Date(95,12,17)

Date.prototype.description=null

today.description="Oh what a beautiful mornin\'"

birthday.description="The day you were born"

After you set a property for the prototype, all subsequent objects created with Date() will have the property:

startDate=new Date()

startDate.description="Started the daily grind"


reload method

(JavaScript 1.1)

Forces a reload of the window's current document.

Syntax

location.reload([true])

true forces an unconditional HTTP GET of the document from the server. This should not be used unless you have reason to believe that disk and memory caches are off or broken, or the server has a new version of the document (possibly it is generated by a CGI on each request).

Description

The reload method forces a reload of the document specified by the URL in the location.href property.

This method uses the same policy that the Navigator's Reload button uses (Once per Session, Every Time, or Never). The user sets the default value of this policy by choosing Network Preferences from the Options menu and specifying Verify Documents on the Cache tab of the Preferences dialog box.

The reload method does not force a transaction with the server, unless the user has set the preference to Every Time, in which case it does a "conditional GET" request using an If-modified-since HTTP header, to ask the server to return the document only if its last-modified time is newer than the time the client keeps in its cache. In other words, reload will reload from the cache, unless the user has specified Every Time and the document has changed on the server since it was last loaded and saved in the cache.

In event handlers, you must specify window.location.reload() instead of simply using location.reload(). Due to the scoping of static objects in JavaScript, a call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL.


replace method

(JavaScript 1.1)

Loads the specified URL over the current history entry.

Syntax

location.replace("URL")

URL specifies the URL to load.

Description

The replace method loads the specified URL over the current history entry, so after the replace method is used, the user cannot navigate to the previous URL by using Navigator's Back button.

In event handlers, you must specify window.location.replace() instead of simply using location.replace(). Due to the scoping of static objects in JavaScript, a call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL.


reset method

(JavaScript 1.1)

Simulates a mouse click on a reset button for the calling form.

Syntax

formName.reset()

Description

The reset method restores a form element's default values. A reset button does not need to be defined for the form.


reverse method

(JavaScript 1.1)

Transposes the elements of an array: the first array element becomes the last and the last becomes the first.

Syntax

arrayName.reverse()

arrayName is the name of an Array object or a property of an existing object.

Description

The reverse method transposes the elements of the calling array object.

Examples

The following example creates an array myArray, containing three elements, then reverses the array.

myArray = new Array("one", "two", "three")

myArray.reverse()

This code changes myArray so that:

myArray[0] is "three"

myArray[1] is "two"

myArray[2] is "one"


scroll method

(JavaScript 1.1)

Scrolls a window to a specified coordinate.

Syntax

windowReference.scroll(x-coordinate,y-coordinate)

x-coordinate is an integer representing the x-coordinate in pixels.

y-coordinate is an integer representing the y-coordinate in pixels.

Description

JavaScript does not reflect document dimensions in pixels, so when using the scroll method, you must hardcode the x and y coordinates. A document's upper left coordinates are 0,0.

Examples

The following example scrolls the current window to the coordinates 50,100.

 window.scroll(50,100)


sort method

(JavaScript 1.1)
Sorts the elements of an array.

Syntax

arrayName.sort(compareFunction)

arrayName is the name of an Array object or a property of an existing object.
compareFunction specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

Description

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" comes before "9" in lexicographic order, but if you are comparing numbers 9 needs to come before 80.
If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

•	If compareFunction(a, b) is less than zero, sort b to a lower index than a.

•	If compareFunction(a, b) returns zero, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.

•	If compareFunction(a, b) is greater than zero, sort b to a higher index than a.


split method

(JavaScript 1.1)
Splits a String object into an array of strings by separating the string into substrings.

Syntax

stringName.split([separator])

stringName is any string or a property of an existing object.
separator specifies the character to use for separating the string. The separator is treated as a string. If separator is omitted, the array returned contains one element consisting of the entire string.

Description

The split method returns the new array.

Examples

The following example defines a function that splits a string into an array of string using the specified separator. After splitting the string, the function displays messages indicating the original string (before the split), the separator used, the number of elements in the array, and the individual array elements.

function splitString (stringToSplit,separator) {

   arrayOfStrings = stringToSplit.split(separator)

   document.write ('<P>The original string is: "' + stringToSplit + '"')

   document.write ('<BR>The separator is: "' + separator + '"')

   document.write ("<BR>The array has " + arrayOfStrings.length + " elements: ")

   for (var i=0; i < arrayOfStrings.length; i++) {

      document.write (arrayOfStrings[i] + " / ")

   }

}

var tempestString="Oh brave new world that has such people in it."

var monthString="Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"

var space=" "

var comma=","

splitString(tempestString,space)

splitString(tempestString)

splitString(monthString,comma)


src property

(JavaScript 1.1)
A string specifying the URL of an image to be displayed in a document.

Syntax

imageName.src

imageName is either the name of an Image object or an element in the images array.

Description

The src property initially reflects the SRC attribute of the <IMG> tag. Setting the src property begins loading the new URL into the image area (and aborts the transfer of any image data that is already loading into the same area). Therefore, if you plan to alter the lowsrc property, you should do so before setting the src property. If the URL in the src property references an image that is not the same size as the image cell it is loaded into, the source image is scaled to fit.

When you change the src property of a displayed image, the new image you specify is displayed in the area defined for the original image. For example, suppose an Image object originally displays the file beluga.gif:

If you set myImage.src='seaotter.gif', the image seaotter.gif is displayed in the same space originally used by beluga.gif, even if seaotter.gif is not the same size as beluga.gif.
You can change the src property at any time.


suffixes property

(JavaScript 1.1)

Property of Plug-in object.


taint function

(JavaScript 1.1)

Adds tainting to a property.

Syntax

taint(propertyName)

propertyName is the property to taint.


toString method

(JavaScript 1.1)

Converts an object into a string.

Syntax

objectName.toString([radix])

objectName is the object to convert to a string.

radix specifies the base to use for representing numeric values.

Description

Every object has a toString method that is called when it is to be represented as a text value. toString is also used when an object is referenced in a string concatenation. You can also use toString within your own code to convert an object into a string.

If an object has no string value, its toString method will return "[object type]" where type is the object type. For example, if the following Image object named "sealife" exists, sealife.toString() will return [object Image].

When used with an array, toString joins the array and returns one string containing each array element separated by commas.

For Function objects, toString decompiles the function back into a canonical source string.


type property

(JavaScript 1.1)

For form elements created with the <INPUT>, <SELECT>, or <TEXTAREA> tags, a string specifying the type of form element. For mimeType objects, the name of the MIME type.

Syntax

1. objectName.type
2. mimeTypes[index].type

objectName is either the value of the NAME attribute of a form element object (button, checkbox, hidden, password, radio, reset, select, submit, text, or textarea) or an element in the elements array.

The value of the type property is assigned to form elements as follows:

HTML element	Value of type property
INPUT TYPE="button"	"button"
INPUT TYPE="checkbox"	"checkbox"
INPUT TYPE="file"	"file"
INPUT TYPE="hidden"	"hidden"
INPUT TYPE="password"	"password"
INPUT TYPE="radio"	"radio"
INPUT TYPE="reset"	"reset"
INPUT TYPE="submit"	"submit"
INPUT TYPE="text"	"text"
SELECT	"select-one"
SELECT MULTIPLE	"select-multiple"
TEXTAREA	"textarea"


typeof operator

(JavaScript 1.1)

Returns a string indicating the type of the unevaluated operand.

Syntax

1. typeof operand
2. typeof (operand)

operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.


untaint function

(JavaScript 1.1)

Removes tainting from a property.

Syntax

untaint(propertyName)

propertyName is the property to remove tainting from.


void operator

(JavaScript 1.1)
Specifies an expression to be evaluated without returning a value.

Syntax

1. javascript:void (expression)
2. javascript:void expression

expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.

Description

Use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.

The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to 0, but that has no effect in JavaScript.

<A HREF="javascript:void(0)">Click here to do nothing</A>

The following code creates a hypertext link that submits a form when the user clicks it.

<A HREF="javascript:void(document.form.submit())">Click here to submit</A>


vspace property

(JavaScript 1.1)
A string specifying a margin in pixels between the top and bottom edges of an image and the surrounding text. (read-only)

Syntax

imageName.vspace

imageName is either the name of an Image object or an element in the images array.

Description

The vspace property reflects the VSPACE attribute of the <IMG> tag. For images created with the Image() constructor, the value of the vspace property is 0.


width property

(JavaScript 1.1)
A string specifying the width of an image either in pixels or as a percentage of the window width. (read-only)

Syntax

imageName.width

imageName is either the name of an Image object or an element in the images array.

Description

The width property reflects the WIDTH attribute of the <IMG> tag. For images created with the Image() constructor, the value of the width property is the actual, not the displayed, width of the image.


opener property

(JavaScript 1.1)

Specifies the window of the calling document when a window is opened using the open method.

Syntax

window.opener

Description

When a source document opens a destination window by calling the open method, the opener property specifies the window of the source document. Evaluate the opener property from the destination window.

This property persists across document unload in the opened window.

You might want to clear the opener property to free otherwise closed windows in a chain of openers leading to the current one.

You can change the opener property at any time.

Examples

The following code closes the window that opened the current window.

window.opener.close()


plugins property

(JavaScript 1.1)

An array of all plug-ins currently installed on the client.


request object (LiveWire)
request object

Contains data specific to the current client request.

Description

LiveWire creates a request object each time the client makes a request of the server. LiveWire destroys the request object after the server responds to the request, typically by providing the requested page.

The properties listed below are read-only properties that are initialized automatically when a request object is created. In addition to these predefined properties, you can create custom properties to store application-specific data about the current request.

Custom properties

You can create a property for the request object by assigning it a name and a value. For example, you can create a request property to store the date and time that a request is received so you can enter the date into the page content. You can also create request object properties by encoding them in a URL. When a user navigates to the URL by clicking its link, the properties are created and instantiated to values that you specify. The properties are valid on the destination page.

Use the following syntax to encode a request property in a URL:

<A HREF="URL?propertyName=value[&propertyName=value...]">

where:

URL is the URL the page that will get the new request properties.

propertyName is the name of the property you are creating.

value is the initial value of the new property.

Use escape to encode non-alphanumeric values in the URL string.

Examples

The following example creates the requestDate property and initializes it with the current date and time:

request.requestDate = new Date()


addClient function (LiveWire)
addClient function

Preserves client object property values when generating dynamic URLs or using redirect if using URL encoding for client object maintenance.

Syntax

addClient(URL)

URL is a string representing a URL.

Description

The addClient function is a top-level LiveWire function that is not associated with any object.

Use addClient to preserve client object property values when you use redirect or generate dynamic links if an application is using client URL encoding or server URL encoding to maintain the client object.

If an application does not use a URL encoding scheme, you do not have to use the addClient function. Because an application may be modified to use a URL encoding scheme in the future, however, it is safer to code the application "defensively" with addClient.

Examples

In the following example, addClient is used with the redirect function to redirect a browser:

redirect(addClient("mypage.html"))

In the following example, addClient preserves client object property values when a link is dynamically generated:

<A HREF=\QaddClient("page" + project.pageno + ".html")\Q>
   Jump to new page</A>


agent property (LiveWire)
agent property

Provides name and version information about the client software. (read-only)

Syntax

request.agent

Description

The agent property identifies the client software. Use this information to conditionally employ certain features in an application. The value of the agent property is the same as the value of the userAgent property of the client-side navigator object.

Examples

The following example displays client information for Navigator 2.0 on Windows NT:

write(request.agent)
Displays "Mozilla/2.0 (WinNT;I)"

The following example evaluates the request.agent property and runs the oldBrowser procedure for clients other than Navigator 2.0. If the browser is Navigator 2.0, the currentBrowser function executes.

<SERVER>
var agentVar=request.agent
if (agentVar.indexOf("2.0")==-1)
   oldBrowser()
else
   currentBrowser()
</SERVER>


beginTransaction method (LiveWire)
beginTransaction method

Begins a SQL transaction.

Syntax

database.beginTransaction()

Description

The beginTransaction method starts a new database transaction. You can group actions that modify the database within this transaction and then either commit or roll back the transaction with the commitTransaction or rollbackTransaction methods. A nested transaction occurs when you issue a second beginTransaction method before committing or rolling back the first transaction. LiveWire does not support nested transactions. If you create a nested transaction, the next commitTransaction or rollbackTransaction commits or rolls back all actions since the first beginTransaction.

The beginTransaction method returns a status code based on a database server message to indicate whether the method completed successfully. If successful, the method returns a zero; otherwise, it returns a nonzero integer to indicate the reason it failed.

Examples

database.beginTransaction();
videoReturn = database.cursor("SELECT * FROM rentals WHERE
   customerId = " + request.customerID + " AND
   videoId = " + request.videoID, true);
videoReturn.next()
videoReturn.returndate = today;
x = videoReturn.updateRow("rentals");
if (x == 0) {
   database.commitTransaction() }
else {
   database.rollbackTransaction() }
videoReturn.close();


blob function (LiveWire)
blob function

Assigns BLOb data to a column in a cursor.

Syntax

cursorName.cursorColumn=blob(blobFileName)

cursorName is the name of a cursor object.

cursorColumn is the name of a column in the cursor containing BLOb data.

blobFileName is the full path and name of a file containing BLOb data.

Description

The blob function is a top-level LiveWire function that is not associated with any object.

The blob function assigns BLOb data to a column by specifying the name and path of a file that contains the BLOb. Use the blob function to update or insert a row in a cursor that contains a BLOb column.

Examples

The following example updates a photograph in the photo column of the customerSet cursor. The cursor contains a single row, specified by the customer.ID value.

customerSet = database.cursor("SELECT * FROM customer WHERE
   customer.ID = " + request.customerID
customerSet.next()
customerSet.photo = blob("c:/data/customer/photo/johnson.gif")
customerSet.updateRow("customer")


blobImage method (LiveWire)
blobImage method

Displays a BLOb from a database as if it were in an IMG tag.

Syntax

cursorName.cursorColumn.blobImage(format [, altText] [, align]
   [, widthPixels] [, heightPixels] [, borderPixels] [,ismap])

Description

The blobImage method retrieves BLOb image data from a database column and displays it in an IMG tag. Most of the parameters of blobImage correspond to attributes of the IMG tag:

Examples

The following example creates a cursor from the rockStarBios table and uses blobImage to display an image retrieved from the photos column:

cursor = database.cursor("SELECT * FROM rockStarBios
   WHERE starID = 23")
while(cursor.next()) {
   write(cursor.photos.blobImage("gif", , left, 30, 30, ,false))
}
cursor.close()


blobLink method (LiveWire)
blobLink method

Creates a hyperlink to an image or another type of binary data.

Syntax

cursorName.cursorColumn.blobLink(mimeType, linkText)

cursorName is the name of a cursor object.

cursorColumn is the name of a column in the cursor containing BLOb data.

mimeType is a string specifying the MIME type of the binary data.

linkText is any JavaScript string expression representing the text to display in the link.

Description

The blobLink method places the BLOb from the specified row and column of the cursor into a temporary file in memory and creates a hyperlink to the BLOb data, in an A tag. Use the blobLink method when you don't want to display graphics immediately (to reduce bandwidth requirements), or to provide a link to an audio clip or other multimedia content that is not viewable inline. LiveWire releases the temporary file that blobLink creates after either of the following has occurred: (1) the user clicks the link, or (2) 60 seconds following the request processing have elapsed. Because LiveWire keeps the binary data that blobLink retrieves from the database in active memory, requests that retrieve a large amount of binary data can exceed dynamic memory on the server. Use discretion when retrieving binary data from databases.

Examples

The following example creates a cursor from the rockStarBios table and uses blobLink to create links to images retrieved from the photos column:

write("Click a link to display an image:<P>")
cursor = database.cursor("select * from rockStarBios")
while(cursor.next()) {
   write(cursor.photos.blobLink("image/gif", "Image " + cursor.id))
   write("<BR>")
}
cursor.close()


byteToString method (LiveWire)
byteToString method

Converts a number that represents a byte into a string.

Syntax

File.byteToString(number)
number is a number that represents a byte.

Description

Use the stringToByte and byteToString methods to convert data between binary and ASCII formats. The byteToString method converts the number argument into a string. This is a static method of the File object; you call this method without specifying the name of a specific File object. If the argument you pass into the byteToString method is not a number, the method returns an empty string.

Examples

// Create the source File object
source = new File("c:/data/source.txt")

// If the source file opens successfully, create a target file
if (source.open("r")) {
   target = new File("c:/data/target.txt")
   target.open("w")

// Copy the source file to the target
   while (!source.eof()) {
      data = File.byteToString(source.readByte())
      target.write(data);
   }
   source.close()
}
   target.close()


callC function (LiveWire)
callC function

Calls an external function and returns the value the external function returns.

Syntax

callC(JSFunctionName, arguments...)

JSFunctionName is the name of the function as it is identified with RegisterCFunction.
arguments is a comma-separated list of arguments to the external function. The arguments can be any JavaScript values: strings, numbers, or Boolean values. The number of arguments must match the number of arguments required by the external function.

Description

The callC function is a top-level LiveWire function that is not associated with any object.
The callC function returns the string value that the external function returns; callC can only return string values.

Examples

The following example assigns a value to the variable isRegistered according to whether the attempt to register the external function echoCCallArguments succeeds or fails. If isRegistered is true, the callC function executes.

var isRegistered =
   registerCFunction("echoCCallArguments",
   "c:mypathmystuff.dll",
   "mystuff_EchoCCallArguments")
if (isRegistered == true) {
   var returnValue =
   callC("echoCCallArguments","first arg", 42,true,"last arg")
   write(returnValue)
}


clearError method (LiveWire)
clearError method

Clears the current file error status.

Syntax

fileObjectName.clearError()

fileObjectName is the name of a File object.

Description

The clearError method clears both the file error status (the value returned by the error method) and the value returned by the eof method.


client object (LiveWire)
client object

Contains data specific to an individual client.

Description

LiveWire automatically creates a client object each time an unknown client accesses an application. LiveWire creates a separate client object for each individual client that requests a page from the server.

All requests by one client use the same client object, as long as those requests occur within the lifetime of that client object. By default, a client object persists until the associated client has been inactive for ten minutes. You can use the expiration method to change this default lifetime or the destroy method to explicitly destroy the client object.

Use the client object to maintain data that is specific to an individual client. Although many clients can access an application simultaneously, the individual client objects keep their data separate. Each client object can track the progress of an individual client across multiple requests to the same application.

Properties

The client object has no predefined properties. You create custom properties to contain any client-specific data that is required by an application. LiveWire does not save client objects that have no property values.
You can create a property for the client object by assigning it a name and a value. For example, you can create a client property to store a customer ID at the beginning of an application so a user does not have to enter it with each request.

Examples

This example dynamically assigns a customer ID number that is used for the lifetime of an application session. The assignId function creates an ID based on the user's IP address, and the customerId property saves the ID.

<SERVER>client.customerId = assignId(request.ip)</SERVER>


close (cursor object) method (LiveWire)
close (cursor object) method

Closes a cursor.

Syntax

cursorName.close()

cursorName is the name of a cursor object.

Description

The close method closes a cursor and releases the memory it uses. If you do not explicitly close a cursor with the close method, LiveWire automatically closes all open cursors at the end of each client request.

Examples

The following example creates the rentalSet cursor, performs certain operations on it, and then closes it with the close method.

// Create a cursor object
rentalSet = database.cursor("SELECT * FROM rentals")

// Perform operations on the cursor
cursorOperations()

//Close the cursor
rentalSet.close()


close (File object) method (LiveWire)
close (File object) method

Closes an open file on the server.

Syntax

fileObjectName.close()

fileObjectName is the name of a File object.

Description

When your application is finished with a file, you should close the file by calling the close method. If the file is not open, the close method fails. This method returns true if it is successful; otherwise, it returns false.


columnName method (LiveWire)
columnName method

Returns the name of a column in a cursor.

Syntax

cursorName.columName(index)

cursorName is the name of a cursor object.
index is an integer representing the ordinal number of the column, starting with zero.

Description

The columnName method returns the name of each column in a cursor.

Examples

The following example assigns the name of the first column in the customerSet cursor to the variable header:

customerSet=database.cursor(SELECT * FROM customer ORDER BY name)
header = customerSet.columnName(0)


columns method (LiveWire)
columns method

Returns the number of columns in a cursor.

Syntax

cursorName.columns()

cursorName is the name of a cursor object.

Description

The columns method returns the number of columns in a cursor object. You can use the columns method with the cursorColumn array to iterate over each column in a cursor.

Examples

The following example returns the number of columns in the cursor called custs:

custs.columns()


commitTransaction method (LiveWire)
commitTransaction method

Commits the active transaction.

Syntax

database.commitTransaction()

Description

The commitTransaction method ends the current database transaction and commits all actions since the previous beginTransaction method. If there is no active transaction (that is, if the application has not issued a beginTransaction), commitTransaction is ignored. The commitTransaction method returns a status code based on a database server message to indicate whether the method completed successfully. If successful, the method returns a zero; otherwise, it returns a nonzero integer to indicate the reason it failed.


connect method (LiveWire)
connect method

Connects an application to a database and creates a database object.

Syntax

database.connect("type", "server", "user", "password", "database")

type is the database type, either "INFORMIX," "ORACLE," "SYBASE," or "ODBC."
server is the name of the database server. The server name typically is established when the database is installed. For ODBC, this is the name of the ODBC service.
user is the user name you use to log in to the database. Some RDBMS systems require this to be the same as your operating system login name; other systems maintain their own collections of valid user names.
password is the password you use to log in to the database. If the database does not require a password, use an empty string.
database is the name of the database you want to access, if your database server supports multiple databases. If multiple databases are not supported, use an empty string.

Description

To connect to a database, use the database object's connect method.

Examples

The following if condition determines if an application is already connected to a database. If not, the connect method connects to an Informix database named mydb, on a server named blue, with user name ADMIN, and the password MANAGER.

if (database.connected()) {
   isConnectedRoutine() }
else {
   database.connect("INFORMIX", "blue", "ADMIN", "MANAGER", "mydb") }


connected method (LiveWire)
connected method

Determines whether an application is connected to a database.

Syntax

database.connected()

Description

The connected method determines if an application is currently connected to a database. This method returns true if the application is connected; otherwise, it returns false.

Examples

The following example uses an if condition to determine if an application is connected to a database server. If the application is connected, the isConnectedRoutine function runs; if the application is not connected, the isNotConnected routine runs.

if(database.connected()) {
   isConnectedRoutine() }
else {
   isNotConnectedRoutine() }


cursor method (LiveWire)
cursor method

Creates a cursor object.

Syntax

cursorName = database.cursor("sqlStatement",[updatable])

cursorName is the name of the cursor object you are creating.
sqlStatement is a JavaScript string representing a SQL SELECT statement supported by the database server.
updatable is a Boolean parameter indicating if the cursor is updatable.

Description

The cursor method creates a cursor object that contains the answer set returned by a SQL SELECT statement. The SELECT statement is passed to the cursor method as the sqlStatement argument.

Examples

The following example creates the updatable cursor custs and returns the columns ID, CUST_NAME, and CITY from the customer table:

custs = database.cursor("SELECT ID, CUST_NAME, CITY
   FROM customer", true)


cursor object (LiveWire)
cursor object

Contains the answer set returned by a SQL SELECT statement.

Syntax

To create a cursor object:

cursorName = database.cursor("sqlStatement",[updateable])

cursorName is the name you give the cursor object.
index is an integer representing the ordinal number of the column, starting with zero.
cursorColumn is the name of a column in the cursor; it is the same as the name of the column in the table.
propertyName is one of the properties listed below.
methodName is one of the methods listed below.

Description

A cursor object contains the data returned by a SQL SELECT statement.

Examples

The following example creates the customerSet cursor object containing the id, name, and city rows from the customer table. The next method moves the pointer to the first row of the cursor.

// Create a cursor object
customerSet = database.cursor("SELECT id, name, city FROM customer")
// Navigate to the first row
customerSet.next()
write(customerSet.id + "<BR>")
write(customerSet.name + "<BR>")
write(customerSet.city + "<BR>")
// Close the cursor
customerSet.close()

The id, name, and city columns become the cursorColumn properties customerSet.id, customerSet.name, and customerSet.city. Because the pointer is in the first row of the cursor, the write method displays the values of these properties for the first row.


cursorColumn property (LiveWire)
cursorColumn property

An array of objects corresponding to the columns in a cursor.


database object (LiveWire)
database object

Lets an application interact with a relational database.

Syntax

To create a database object:

database.connect("type", "server", "user", "password", "database")

Description

LiveWire creates a database object when an application connects to a database server. Each application can have only one database object. Use the database object to interact with the database on the server.

Examples

The following example creates a database object and opens a standard connection to the customer database on an Informix server. The name of the server is blue, the user name is ADMIN, and the password is MANAGER.

database.connect("INFORMIX", "blue", "ADMIN", "MANAGER", "inventory")


debug function (LiveWire)
debug function

Displays a LiveWire expression in the trace facility.

Syntax

debug(expression)

expression is any valid LiveWire expression.

Description

The debug function is a top-level LiveWire function that is not associated with any object.

Use this function to display the value of an expression for debugging purposes. The value is displayed in the trace facility following the brief description "Debug message:".

Examples

The following example displays the value of the variable data:

debug("The final value of data is " + data)


deleteRow method (LiveWire)
deleteRow method

Deletes a row from a database table.

Syntax

cursorName.deleteRow("tableName")

cursorName is the name of a cursor object.

tableName is the name of a database table.

Description

The deleteRow method uses an updatable cursor to delete the current row from the specified table.

The deleteRow method returns a status code based on a database server message to indicate whether the method completed successfully. If successful, the method returns a zero; otherwise, it returns a nonzero integer to indicate the reason it failed.

Examples

In the following example, the deleteRow method removes a customer from the customer database. The cursor method creates the customerSet cursor containing a single row; the value for customer.ID is passed in as a request object property. The next method moves the pointer to the only row in the cursor, and the deleteRow method deletes the row.

   database.beginTransaction()
   customerSet = database.cursor("select * from customer where
      customer.ID = " + request.ID,true)
   customerSet.next()
   statusCode = customerSet.deleteRow("customer")
   customerSet.close()
   if (statusCode == 0) {
      database.commitTransaction() }
   else {
      database.rollbackTransaction() }


destroy method (LiveWire)
destroy method

Destroys a client object.

Syntax

client.destroy()

Description

The destroy method explicitly destroys the client object that issues it and removes all properties from the client object. If you do not explicitly issue a destroy method, LiveWire automatically destroys the client object when its lifetime expires. The expiration method sets the lifetime of a client object; by default, the lifetime is ten minutes.

If you are using client-cookies to maintain the client object, destroy eliminates all client property values, but it does not affect what is stored in the Navigator's cookie file. Use expiration with an argument of zero seconds to remove all client properties stored in the cookie file.

When using client URL to maintain the client object, destroy will remove all client properties after the method call. However, any links in a page before the call to destroy will retain properties in their URLs. Therefore, you should generally call destroy either at the top or bottom of the page when using client URL maintenance. For more information, see the next section.

Examples

The following method destroys the client object that calls it:

<SERVER>client.destroy()</SERVER>


disconnect method (LiveWire)
disconnect method

Disconnects an application from a database and destroys the database object.

Syntax

database.disconnect()

Description

Use the disconnect method to close a database connection. When an application is disconnected from a database, it cannot create cursors or use database methods.

Examples

The following example uses an if condition to determine if an application is connected to a database server. If the application is connected, the application calls the disconnect method; if the application is not connected, the isNotConnected routine runs.

if(database.connected()) {
   database.disconnect() }
else {
   isNotConnectedRoutine() }


eof method (LiveWire)
eof method

Determines whether the pointer is beyond the end of an open file.

Syntax

fileObjectName.eof()

fileObjectName is the name of a File object.

Description

Use the eof method to determine whether the position of the pointer is beyond the end of a file.

A call to setPosition resulting in a location greater than fileObjectName.getLength places the pointer beyond the end of the file. Because all read operations also move the pointer, a read operation that reads the last byte of data (or character) in a file positions the pointer beyond the end of the file.

The eof method returns true if the pointer is beyond the end of the file; otherwise, it returns false.

Examples

In this example, a while loop executes until the pointer is positioned past the end of the file. While the pointer is not positioned past the end of the file, the readln method reads the current line, and the write method displays it. The last readln method positions the pointer past the end of the file, ending the while loop.

x = new File("c:/data/userInfo.txt")
if (x.open("r")) {
   while (!x.eof()) {
      line = x.readln()
      write(line+"<br>");
   }
   x.close();
}


error method (LiveWire)
error method

Returns the current error status.

Syntax

fileObjectName.error()

fileObjectName is the name of a File object.

Description

The error method returns one of the following values: If the file specified in fileObjectName is open, the error method returns the error status; otherwise, it returns -1. The error status is nonzero when an error occurs; otherwise, it is zero. Specific error status codes are platform-dependent.

Examples

The following example uses the error method in an if statement to take different actions depending on whether a call to the open method succeeded. After the if statement completes, the error status is reset with the clearError method.

userInput = new File("c:/data/input.txt")
userInput.open("w")
if (userInput.error() == 0) {
   fileIsOpen() }
else {
   fileIsNotOpen() }
userInput.clearError()


execute method (LiveWire)
execute method

Executes a SQL statement that does not return an answer set.

Syntax

database.execute(sqlStatement)

sqlStatement is an expression that evaluates to a SQL statement supported by the database server.

Description

The execute method lets you execute a SQL statement that does not return an answer set, such as INSERT, UPDATE, and DELETE statements. The SQL statement passed as a parameter to the execute method is committed automatically, unless you explicitly start a transaction with the beginTransaction method.

Use the cursor or SQLTable methods to execute a SQL statement that returns an answer set.

The execute method returns a status code based on a database server message to indicate whether the method completed successfully. If successful, the method returns a zero; otherwise, it returns a nonzero integer to indicate the reason it failed.

Examples

In the following example, the execute method is used to delete a customer from the customer table.

if(request.ID != null)
   {
   database.execute("delete from customer
      where customer.ID = " + request.ID)
   }


exists method (LiveWire)
exists method

Determines if a file exists.

Syntax

fileObjectName.exists()

fileObjectName is the name of a File object.

Description

The exists method returns true if the file exists; otherwise, it returns false.

Examples

The following example uses an if statement to take different actions depending on whether a physical file exists. If the file exists, LiveWire opens it and calls the writeData function. If the file does not exist, LiveWire calls the noFile function.

dataFile = new File("c:/data/mytest.txt")

if (dataFile.exists() ==true)
   {
   dataFile.open("w")
   writeData()
   dataFile.close()
   }
else
   {
   noFile()
   }


expiration method (LiveWire)
expiration method

Specifies the duration of a client object.

Syntax

client.expiration(seconds)

seconds is an integer representing the number of seconds of client inactivity before the client object expires.

Description

By default, LiveWire destroys the client object after the client is inactive for ten minutes. This default lifetime lets LiveWire clean up client objects that are no longer necessary.

Use the expiration method to explicitly control the expiration of a client object, making it longer or shorter than the default. You must use expiration in each page of an application for which you want a client expiration other than the default. Any page that does not specify an expiration will use the default of ten minutes.

Examples

The following example extends the amount of client inactivity before expiration to one hour. This code is issued when an application is first launched.

<SERVER>client.expiration(3600)</SERVER>


File object (LiveWire)
File object

Lets an application interact with a physical file on the server.

Syntax

To create a File object:

fileObjectName = new File("path")

To use a File object:

fileObjectName.methodName

fileObjectName is the name of the new File object.

path is the path and filename in the format of the server's file system (not a URL path).

methodName is any of the methods listed below.

Description

You can use the File object to write to or read from a file on the server. For security reasons, you cannot programmatically access the file system of client machines.

You can use the File object to generate persistent HTML or data files without using a database server. Information stored in a file, unlike information stored in a LiveWire object, is preserved when the server goes down.

Exercise caution when using the File object. An application can read and write files anywhere the operating system allows. If you create an application that writes to or reads from your file system, you should ensure that users cannot misuse this capability.

Specify the full path, including the filename, for the path parameter of the File object you want to create. The path must be an absolute path; do not use a relative path. If the physical file specified in the path already exists, LiveWire references it when you call methods for the object. If the physical file does not exist, you can create it by calling the open method.

Examples

The following example creates the File object userInfo that references a physical file called info.txt. The info.txt file resides in the same directory as the application's .web file:

userInfo = new File("info.txt")


flush function (LiveWire)
flush function

Sends data from previously issued write functions to the client.

Syntax

flush()

Description

To improve performance, LiveWire buffers the output of the write function and sends it to the client in 64K blocks. The flush function sends to the client any data that is in the buffer as a result of previously issued write functions.

Use the flush function to control when data is sent to the client. For example, call the flush function before an operation that creates a delay, such as a database query. If a database query retrieves a large number of rows, you can flush the buffer after retrieving a small number of rows to prevent long delays in displaying data.

Because the flush function updates the client's cookie file as part of the HTTP header, you should perform any changes to the client object before flushing the buffer, if you are using client cookie to maintain the client object.

Do not confuse the flush method of the File object with the top-level flush function. The flush function is a top-level LiveWire function that is not associated with any object.

Examples

The following example iterates through a text file and outputs each line in the file, preceded by a line number and five spaces. The flush function then causes the client to display the output.

while (!In.eof()) {
   AscLine = In.readln();
   if (!In.eof())
      write(LPad(LineCount + ": ", 5), AscLine, "n");
   LineCount++;
   flush();
}


flush method (LiveWire)
flush method

Writes the content of the internal buffer to a file.

Syntax

fileObjectName.flush()

fileObjectName is the name of a File object.

Description

When you write to a file with any of the File object methods (write, writeByte, or writeln), the data is buffered internally. The flush method writes the buffer to the physical file. The flush method returns true if it is successful; otherwise, it returns false.

Do not confuse the flush method of the File object with the top-level flush function. The flush function flushes a buffer of data and causes it to display in the client browser; the flush method flushes a buffer of data to a physical file.


getLength method (LiveWire)
getLength method

Returns the length of a file.

Syntax

fileObjectName.getLength()

fileObjectName is the name of a File object.

Description

If this method is successful, it returns the number of bytes in a binary file or characters in a text file; otherwise, it returns -1.

Examples

The following example copies a file one character at a time. This example uses getLength as a counter in a for loop to iterate over every character in the file.

// Create the source File object
source = new File("c:/data/source.txt")
// If the source file opens successfully, create a target file
if (source.open("r")) {
   target = new File("c:/data/target.txt")
   target.open("a")
// Copy the source file to the target
   for (var x = 0; x < source.getLength(); x++) {
   source.setPosition(x)
   data = source.read(1)
   target.write(data)
   }
   source.close()
}
   target.close()


host property (LiveWire)
host property

A string specifying the server name, subdomain, and domain name. (read-only)

Syntax

server.host

Description

The host property specifies a portion of a URL. The host property is a substring of the hostname property. The hostname property is the concatenation of the host and port properties, separated by a colon. When the port property is 80 (the default), the host property is the same as the hostname property.


hostname property (LiveWire)
hostname

Property. A string containing the full hostname of the server, including the server name, subdomain, domain, and port number. (read-only)

Syntax

server.hostname

Description

The hostname property specifies a portion of a URL. The hostname property is the concatenation of the host and port properties, separated by a colon. When the port property is 80 (the default), the host property is the same as the hostname property.


imageX property (LiveWire)
imageX property

The horizontal position of the mouse pointer when user clicked the mouse over an image map. (read-only)

Syntax

request.imageX

Description

The ISMAP attribute of the IMG tag indicates a server-based image map; when the user clicks the mouse when the pointer is over an image map, the horizontal and vertical position of the pointer are returned to the server.

The imageX property returns the horizontal position of the mouse cursor when the user clicks on an image map.

Examples

Suppose you define the following image map:

<A HREF="mapchoice.html">
<IMG SRC="images/map.gif" WIDTH=599 WIDTH=424 BORDER=0 ISMAP
ALT="SANTA CRUZ COUNTY">
</A>

Note the ISMAP attribute that makes the image a clickable map. When the user clicks the mouse on the image, the page mapchoice.html will have properties request.imageX and request.imageY based on the mouse cursor position where the user clicked.


imageY property (LiveWire)
imageY property

The vertical position of the mouse pointer when user clicked the mouse over an image map. (read-only)

Syntax

request.imageY

Description

The imageY property returns the vertical position of the mouse cursor when the user clicks on an image map.


insertRow method (LiveWire)
insertRow method

Inserts a row in a database table.

Syntax

cursorName.insertRow("tableName")

cursorName is the name of a cursor object.

tableName is the name of a database table.

Description

The insertRow method uses an updatable cursor to insert a row in the specified table. The inserted row follows the current row. See the cursor method for information about creating an updatable cursor.

You can specify values for the row you are inserting as follows:

By explicitly assigning values to each column in the cursor and then calling the insertRow method.

By navigating to a row with the next method, explicitly assigning values for some columns, and then calling the insertRow method. Columns that are not explicitly assigned values receive values from the row to which you navigated.

By not navigating to another record and then calling the insertRow method. If you do not issue a next method, columns that are not explicitly assigned values are null.

The insertRow method inserts a null value in any table columns that do not appear in the cursor.

Examples

In some applications, such as a video-rental application, a husband, wife, and children could all share the same account number but be listed under different names. In this example, a user has just added a name to the accounts table and wants to add a spouse's name to the same account.

customerSet = database.cursor("select * from customer", true)
x=true
while (x) {
   x = customerSet.next() }
customerSet.name = request.theName
customerSet.insertRow("accounts")
customerSet.close()


ip property (LiveWire)
ip property

Provides the IP address of the client. (read-only)

Syntax

request.ip

Description

The IP address is a set of four numbers between 0 and 255, for example, "198.217.226.34." You can use the IP address to authorize or record access in certain situations.

Examples

In the following example, the indexOf method evaluates request.ip to determine if it begins with the string "198.217.226.". The if statement executes a different function depending on the result of the indexOf method.

<SERVER>
var ipAddress=request.ip
if (ipAddress.indexOf("198.217.226.")==-1)
   limitedAccess()
else
   fullAccess()
</SERVER>


lock method (LiveWire)
lock method

Locks the project or server object to prevent other clients from modifying or locking it.

Syntax

1. project.lock()
2. server.lock()

Description

You can lock the project or server object to ensure that different clients do not change its properties simultaneously. When an application locks an object, other client requests must wait before they can modify or lock the object.

It is good programming practice to call the unlock method and release an object after calling the lock method. However, LiveWire automatically unlocks an object after the completion of each request to prevent accidental deadlock.


majorErrorCode method (LiveWire)
majorErrorCode method

Returns the major error code returned by the database server.

Syntax

database.majorErrorCode()

Description

When the database methods execute, insertRow, updateRow, deleteRow, beginTransaction, commitTransaction, and rollbackTransaction fail they return a database status code to indicate the reason for failure. When that status code is five (server error) or seven (vendor library error), the majorErrorCode method returns additional information about the failure. The majorErrorCode method returns the major error code returned by the database server or ODBC. For server errors, this value typically corresponds to the server's SQLCODE.

Examples

This example updates the rentals table within a transaction. The updateRow method assigns a database status code to the statusCode variable to indicate whether the method is successful.

database.beginTransaction()
statusCode = cursor.updateRow("rentals")
if (statusCode == 0) {
   database.commitTransaction()
if (statusCode == 5 || statusCode == 7) {
   write("The operation failed to complete.<BR>"
   write("Contact your system administrator with the following:<P>"
   write("The value of statusCode is " + statusCode + "<BR>")
   write("The value of majorErrorCode is " +
      database.majorErrorCode() + "<BR>")
   write("The value of majorErrorMessage is " +
      database.majorErrorMessage() + "<BR>")
   write("The value of minorErrorCode is " +
      database.minorErrorCode() + "<BR>")
   write("The value of minorErrorMessage is " +
      database.minorErrorMessage() + "<BR>") }
   database.rollbackTransaction()
else {
   errorRoutine() }


majorErrorMessage method (LiveWire)
majorErrorMessage method

Returns the major error message returned by the database server.

Syntax

database.majorErrorMessage()

Description

When the database methods execute, insertRow, updateRow, deleteRow, beginTransaction, commitTransaction, and rollbackTransaction fail they return a database status code to indicate the reason for failure. When that status code is five (server error) or seven (vendor library error), the majorErrorMessage method returns additional information about the failure. The majorErrorMessage method returns the major error message returned by the database server or ODBC.


method property (LiveWire)
method property

Provides the HTTP method associated with the request. (read-only)

Syntax

request.method

Description

The value of the method property is the same as the value of the method property of the client-side form object; that is, method reflects the METHOD attribute of the FORM tag. For HTTP 1.0, the method property evaluates to either "get" or "post." Use the method property to determine the proper response to a request.

Examples

The following example executes the postResponse function if the method property evaluates to "post." If method evaluates to anything else, the getResponse function executes.

<SERVER>
if (request.method=="post")
   postResponse()
else
   getResponse()
</SERVER>


minorErrorCode method (LiveWire)
minorErrorCode method

Returns the secondary error code returned by the database vendor library.

Syntax

database.minorErrorCode()

Description

When the database methods execute, insertRow, updateRow, deleteRow, beginTransaction, commitTransaction, and rollbackTransaction fail they return a database status code to indicate the reason for failure. When that status code is five (server error) or seven (vendor library error), the minorErrorCode method returns additional information about the failure.


minorErrorMessage method (LiveWire)
minorErrorMessage method

Returns the secondary message returned by the database vendor library.

Syntax

database.minorErrorMessage()

Description

When the database methods execute, insertRow, updateRow, deleteRow, beginTransaction, commitTransaction, and rollbackTransaction fail they return a database status code to indicate the reason for failure. When that status code is five (server error) or seven (vendor library error), the minorErrorMessage method returns the secondary message returned by the database vendor library.


next method (LiveWire)
next method

Navigates to the next row in a cursor object.

Syntax

cursorName.next()

cursorName is the name of a cursor object.

Description

The next method moves the pointer to the next row in a cursor object. The next method returns false if the current row is the last row in the cursor; otherwise, it returns true. See the cursor object for more information about the pointer.

Use the next method to iterate through the records in a cursor. When the last row in the answer set is the current row, the next method returns false.

Examples

This example uses the next method to navigate to the last row in a cursor. The variable x is initialized to true. When the pointer is in the last row of the cursor, the next method returns false and terminates the while loop.

customerSet = database.cursor("select * from customer", true)

x=true
while (x) {
   x = customerSet.next() }


open method (LiveWire)
open method

Opens a file on the server.

Syntax

fileObjectName.open("mode")

fileObjectName is a string specifying the name of a File object.

mode is a string specifying whether to open the file to read, write, or append, according to the list below.

Description

Use the open method to open a file on the server before you read from it or write to it. If the file is already open, the method fails and has no effect. The open method returns true if it is successful; otherwise, it returns false. The mode parameter is a string that specifies whether to open the file to read, write, or append data:

•	r[b] opens a file for reading. If the file exists, the method succeeds and returns true; otherwise, the method fails and returns false.

•	w[b] opens a file for writing. If the file does not already exist, it is created; otherwise, it is overwritten. This method always succeeds and returns true.

•	a[b] opens a file for appending (writing at the end of the file). If the file does not already exist, it is created. This method always succeeds and returns true.

•	r+[b] opens a file for reading and writing. If the file exists, the method succeeds and returns true; otherwise, the method fails and returns false. Reading and writing commence at the beginning of the file. When writing, characters at the beginning of the file are overwritten.

•	w+[b] opens a file for reading and writing. If the file does not already exist, it is created; otherwise, it is overwritten. This method always succeeds and returns true.

•	a+[b] opens a file for reading and appending. If the file does not already exist, it is created. This method always succeeds and returns true. Reading and appending commence at the end of the file.

If you use the b parameter when you specify the mode, LiveWire opens the file as a binary file. If you do not use the b parameter, LiveWire opens the file as a text file. The b parameter is available only on Windows platforms.

When your application is finished with a file, you should close the file by calling the close method.

Examples

The following example opens the file info.txt so an application can write information to it.

userInfo = new File("c:/data/info.txt")
userInfo.open("w")
writeData()
userInfo.close()


port property (LiveWire)
port property

A string indicating the port number used for the server. (read-only)

Syntax

server.port

Description

The port property specifies a portion of the URL. The port property is a substring of the hostname property. The hostname property is the concatenation of the host and port properties, separated by a colon.

The default value of the port property is 80. When the port property is set to the default, the values of the host and hostname properties are the same.


project object (LiveWire)
project object

Contains data for an entire application.

Description

LiveWire creates a project object when an application starts and destroys the project object when the application or server stops. The typical project object lifetime is days or weeks. Each client accessing the same application shares the same project object. Use the project object to maintain global data for an entire application. Many clients can access an application simultaneously, and the project object lets these clients share information.

LiveWire creates a set of project objects for each distinct Netscape HTTPD process running on the server. Because several server HTTPD processes may be running on different port numbers, LiveWire creates a set of project objects for each process.

You can lock the project object to ensure that different clients do not change its properties simultaneously. When one client locks the project object, other clients must wait before they can modify it. See the lock and unlock methods for complete information.

The project object has no predefined properties. You create custom properties to contain project-specific data that is required by an application.

Examples

This example creates the lastID property and assigns a value to it by incrementing an existing value.

project.lastID = 1 + parseInt(project.lastID, 10)


protocol property (request object) (LiveWire)
protocol property (request object)

Provides the HTTP protocol level supported by the client's software. (read-only)

Syntax

request.protocol

Description

For HTTP 1.0, the protocol value is "HTTP/1.0." Use the protocol property to determine the proper response to a request.

Examples

In the following example, the currentProtocol function executes if request.protocol evaluates to "HTTP/1.0."

<SERVER>
if (request.protocol=="HTTP/1.0"
   currentProtocol()
else
   unknownProtocol()
</SERVER>


protocol property (server object) (LiveWire)
protocol property (server object)

A string indicating the communication protocol used by the server. (read-only)

Syntax

server.protocol

Description

The protocol property specifies the beginning of the URL, up to and including the first colon. The protocol indicates the access method of the URL. For example, a protocol of "http:" specifies HyperText Transfer Protocol.


read method (LiveWire)
read method

Reads data from a file into a string.

Syntax

fileObjectName.read(count)

fileObjectName is the name of a File object.

count is an integer specifying the number of characters to read.

Description

The read method reads the specified number of characters from a file, starting from the current position of the pointer. If you attempt to read more characters than the file contains, the method reads as many characters as possible. This method moves the pointer the number of characters specified by the count parameter. The read method returns the characters it reads as a string.

Use the read method to read information from a text file; use the readByte method to read data from a binary file.

Examples

The following example references the file info.txt, which contains the string "Hello World." The first read method starts from the beginning of the file and reads the character "H." The second read method starts from offset six and reads the characters "World."

dataFile = new File("c:/data/info.txt")
dataFile.open("r")
write("The next character is " + dataFile.read(1) + "<BR>")
dataFile.setPosition(6)
write("The next five characters are " + dataFile.read(5) + "<BR>")
dataFile.close()

This example displays the following information:

The next character is H
The next five characters are World


readByte method (LiveWire)
readByte method

Reads the next byte from an open file and returns its numeric value.

Syntax

fileObjectName.readByte()

fileObjectName is the name of a File object.

Description

The readByte method reads the next byte from a file, starting from the current position of the pointer. This method moves the pointer one byte. The readByte method returns the byte it reads as a number. If the pointer is at the end of the file when you issue readByte, the method returns -1.

Use the readByte method to read information from a binary file. You can use the readByte method to read from a text file, but you must use the byteToString method to convert the value to a string. Generally it is better to use the read method to read information from a text file. You can use the writeByte method to write data read by the readByte method to a file.

Examples

This example creates a copy of a binary file. In this example, a while loop executes until the pointer is positioned past the end of the file. While the pointer is not positioned past the end of the file, the readByte method reads the current byte from the source file, and the writeByte method writes it to the target file. The last readByte method positions the pointer past the end of the file, ending the while loop.

// Create the source File object
source = new File("c:/data/source.gif")
// If the source file opens successfully, create a target file
if (source.open("rb")) {
   target = new File("c:/data/target.gif")
   target.open("wb")
// Copy the source file to the target
   while (!source.eof()) {
      data = source.readByte()
      target.writeByte(data);
   }
   source.close();
}
target.close()


readln method (LiveWire)
readln method

Reads the current line from an open file and returns it as a string.

Syntax

fileObjectName.readln()

fileObjectName is the name of a File object.

Description

The readln method reads the current line of characters from a file, starting from the current position of the pointer. If you attempt to read more characters than the file contains, the method reads as many characters as possible. This method moves the pointer to the beginning of the next line.

The readln method returns the characters it reads as a string.

The line separator characters ("r" and "n" on Windows platforms and "n" on Unix platforms) are not included in the string that the readln method returns. The r character is skipped; n determines the actual end of the line.

Use the readln method to read information from a text file; use the readByte method to read data from a binary file. You can use the writeln method to write data read by the readln method to a file.


redirect function (LiveWire)
redirect function

Redirects the client to the specified URL.

Syntax

redirect(location)

location is the URL to which you want to redirect the client.

Description

The redirect function is a top-level LiveWire function that is not associated with any object. The redirect function redirects the client browser to the URL specified by the location parameter. The value of location can be relative or absolute.

When the client encounters a redirect function, it loads the specified page immediately and discards the current page. The client does not execute or load any HTML or script statements in the page following the redirect function.

Use the addClient function to preserve client object property values if using client URL maintenance.

Examples

The following example uses the redirect function to redirect a client browser:

redirect("http://www.hardRain.com/lw/apps/newhome.html")

The page displayed by the newhome.html link could contain content such as the following:

<H1>New location</H1>
The URL you tried to access has been moved to:<BR>
<LI><A HREF=http://www.hardRain.com/lw/apps/index.html>
   http://www.hardRain.com/lw/apps/index.html</A>
<P>This notice will remain until 12/31/96.


registerCFunction function (LiveWire)
registerCFunction function

Registers an external function for use with a LiveWire application.

Syntax

registerCFunction(JSFunctionName, libraryPath, externalFunctionName)

JSFunctionName is the name of the function as it is called in JavaScript.

libraryPath is the full filename and path of the library, using the conventions of your operating system.

externalFunctionName is the name of the function as it is defined in the library.

Description

Use registerCFunction to make an external function available to a LiveWire application. The function can be written in any language, but you must use C calling conventions. To use an external function in a LiveWire application, register the function with registerCFunction, and then call it with the callC function. Once an application registers a function, you can call the function any number of times.

The registerCFunction function returns true if the external function is registered successfully; otherwise, it returns false. For example, registerCFunction can return false if LiveWire cannot find either the library or the specified function inside the library.

To use a backslash (\) character as a directory separator in the libraryPath parameter, you must enter a double backslash (\\). The single backslash is a reserved character.

registerCFunction is a top-level LiveWire function that is not associated with any object.


rollbackTransaction method (LiveWire)
rollbackTransaction method

Rolls back the active transaction.

Syntax

database.rollbackTransaction()

Description

The rollbackTransaction method rolls back the current transaction and undoes all modifications since the previous beginTransaction. If there is no active transaction (that is, if the application has not issued a beginTransaction), rollbackTransaction is ignored.

The rollbackTransaction method returns a status code based on a database server message to indicate whether the method completed successfully. If successful, the method returns a zero; otherwise, it returns a nonzero integer to indicate the reason it failed.


server object (LiveWire)
server object

Contains global data for the entire server.

Description

LiveWire creates a server object when the server starts and destroys it when the server stops. Every application on a server shares the same server object. Use the server object to maintain global data for the entire server. Many applications can run on a server simultaneously, and the server object lets them share information.

LiveWire creates a server object for each distinct Netscape HTTPD process running on the server.

The properties listed below are read-only properties that are initialized automatically when a server object is created. These properties provide information about the server process. In addition to these predefined properties, you can create custom properties.

You can lock the server object to ensure that different applications do not change its properties simultaneously. When one application locks the server object, other applications must wait before they can modify it. See the lock and unlock methods for complete information.

Examples

The following example displays the values of the predefined server object properties:

<P>server.host = <SERVER>write(server.host);</SERVER>
<BR>server.hostname = <SERVER>write(server.hostname);</SERVER>
<BR>server.protocol = <SERVER>write(server.protocol);</SERVER>
<BR>server.port = <SERVER>write(server.port);</SERVER>

The preceding code displays information such as the following:

server.host = www.myWorld.com
server.hostname = www.myWorld.com:85
server.protocol = http:
server.port = 85


setPosition method (LiveWire)
setPosition method

Positions a pointer in an open file.

Syntax

fileObjectName.setPosition(position [,reference])

fileObjectName is the name of a File object.

position is an integer indicating where to position the pointer.

reference is an integer that indicates a reference point, according to the list below.

Description

Use the setPosition method to reposition the pointer in a file. The position argument is a positive or negative integer that moves the pointer the specified number of bytes relative to the reference argument. Position zero represents the beginning of a file. The end of a file is indicated by fileObjectName.getLength(). The optional reference argument is one of the following values, indicating the reference point for the position:

0: relative to beginning of file.

1: relative to current position.

2: relative to end of file.

Other (or unspecified): relative to beginning of file.

The setPosition method returns true if it is successful; otherwise, it returns false.

Examples

This example moves the pointer from the beginning of the file to offset ten. Because no value for reference is supplied, LiveWire assumes it is zero.

dataFile = new File("c:/data/info.txt")
dataFile.open("r")
dataFile.setPosition(10)
write("The position is " + dataFile.getPosition() + "<BR>")
write("The next character is " + dataFile.read(1) + "<P>")
dataFile.close()


SQLTable method (LiveWire)
SQLTable method

Displays the result of a SQL SELECT statement in an HTML table.

Syntax

database.SQLTable("sqlStatement")

sqlStatement is an expression that evaluates to a SQL SELECT statement supported by the database server.

Description

The SQLTable method is the easiest way to display the output of a database query. The SQLTable method displays the results of a database query in an HTML table. The SQLTable method does not let you explicitly control the format of the output. To customize the appearance of the output, use a database cursor. See the cursor method for information about creating a cursor.

Examples

In the following example, the connect method opens the sample database included with LiveWire, and the SQLTable method queries the videos table. The SQL SELECT statement provided as an argument to the SQLTable method returns all the rows in the videos table sorted by the values in the title field.

database.connect("INFORMIX", "ol_alpha", "guest", "guest", "livewire")
database.SQLTable("SELECT * FROM VIDEOS ORDER BY TITLE")


stringToByte method (LiveWire)
stringToByte method

Converts the first character of a string into a number that represents a byte.

Syntax

File.stringToByte(string)

string is a JavaScript string.

Description

Use the stringToByte and byteToString methods to convert data between binary and ASCII formats. The stringToByte method converts the first character of its string argument into a number that represents a byte. This is a static method of the File object; you call this method without specifying the name of a specific File object. If this method succeeds, it returns the numeric value of the first character of the input string; if it fails, it returns zero.

Examples

In the following example, the stringToByte method is passed "Hello" as an input argument. The method converts the first character, "H," into a numeric value representing a byte.

write("The stringToByte value of Hello = " +
   File.stringToByte("Hello") + "<BR>")
write("Returning that value to byteToString = " +
   File.byteToString(File.stringToByte("Hello")) + "<P>")

The previous example displays the following information:

The stringToByte value of Hello = 72
Returning that value to byteToString = H


unlock method (LiveWire)
unlock method

Unlocks the project or server object.

Syntax

1. project.unlock()
2. server.unlock()

Description

You can lock the project or server object to ensure that different clients do not change its properties simultaneously. When an application locks an object, other client requests must wait before they can modify or lock the object.

It is good programming practice to call the unlock method and release an object after calling the lock method. However, LiveWire automatically unlocks an object after the completion of each request to prevent accidental deadlock.


updateRow method (LiveWire)
updateRow method

Updates the current row of a table with values from the current row in a cursor.

Syntax

cursorName.updateRow(tableName)

cursorName is the name of a cursor object.

tableName is the name of a database table.

Description

The updateRow method lets you use values in the current row of an updatable cursor to modify a table. Before performing an updateRow, you must perform at least one next with the cursor so the current row is set to a row.

Assign values to columns in the current row of the cursor, and then use the updateRow method to update the current row of the table specified by the tableName parameter. Column values that are not explicitly assigned are not changed by the updateRow method.

The updateRow method returns a status code based on a database server message to indicate whether the method completed successfully. If successful, the method returns a zero; otherwise, it returns a nonzero integer to indicate the reason it failed.

Examples

This example uses updateRow to update the returndate column of the rentals table.

// Create a Date object with the value of today's date
today = new Date()

// Create a cursor with the rented video in the answer set
videoReturn = database.cursor("SELECT * FROM rentals WHERE
   customerId = " + request.customerID + " AND
   videoId = " + request.videoID, true)

// Position the pointer on the first row of the cursor
videoReturn.next()

// Assign today's date to the returndate column
videoReturn.returndate = today

// Update the row
videoReturn.updateRow("rentals")


write function (LiveWire)
write function

Generates HTML based on an expression and sends it to the client.

Syntax

write(expression)

expression is a valid JavaScript expression.

Description

The write function causes LiveWire to generate HTML that is sent to the client. The client interprets this generated HTML the same as static HTML.

To improve performance, LiveWire buffers the output of the write function and sends it to the client in large blocks of at most 64Kbytes in size. You can control when data are sent to the client by using the flush function.

The write function is a top-level LiveWire function that is not associated with any object. Do not confuse the write method of the File object with the write function. The write function outputs data to the client; the write method outputs data to a physical file on the server.

Examples

In the following example, the write function is passed a string, concatenated with a variable, concatenated with an HTML BR tag:

write("The operation returned " + returnValue + "<BR>")

If returnValue is fifty-seven, this example displays

The operation returned 57


write method (LiveWire)
write method

Writes data from a string to a file on the server.

Syntax

fileObjectName.write(string)

fileObjectName is the name of a File object.

string is a JavaScript string.

Description

The write method writes the string specified as string to the file specified as fileObjectName. This method returns true if it is successful; otherwise, it returns false.

Use the write method to write data to a text file; use the writeByte method to write data to a binary file. You can use the read method to read data from a file to a string for use with the write method.

Do not confuse the write method of the File object with the write function. The write function outputs data to the client browser; the write method outputs data to a physical file on the server.

Examples

This example creates a copy of a text file, one character at a time.

// Create the source File object
source = new File("c:/data/source.txt")

// If the source file opens successfully, create a target file
if (source.open("r")) {
   target = new File("c:/data/target.txt")
   target.open("w")

// Copy the source file to the target
   while (!source.eof()) {
      data = source.read(1)
      target.write(data);
   }
   source.close();
}
   target.flush()
   target.close()


writeByte method (LiveWire)
writeByte method

Writes a byte of data to a binary file on the server.

Syntax

fileObjectName.writeByte(number)

fileObjectName is the name of a File object.

number is a number that specifies a byte of data.

Description

The writeByte method writes a byte that is specified as number to a file that is specified as fileObjectName. This method returns true if it is successful; otherwise, it returns false.

Use the writeByte method to write data to a binary file; use the write method to write data to a text file. You can use the readByte method to read bytes of data from a file to numeric values for use with the writeByte method.


writeln method (LiveWire)
writeln method

Writes a string and a carriage return to a file on the server.

Syntax

fileObjectName.writeln(string)

fileObjectName is the name of a File object.

string is a JavaScript string.

Description

The writeln method writes the string specified as string to the file specified as fileObjectName. Each string is followed by the carriage return/line feed character "n" ("rn" on Windows platforms). This method returns true if the write is successful; otherwise, it returns false.

Use the writeln method to write data to a text file; use the writeByte method to write data to a binary file. You can use the readln method to read data from a file to a string for use with the writeln method.

Examples

This example creates a copy of a text file, one line at a time.

// Create the source File object
source = new File("c:/data/source.txt")

// If the source file opens successfully, create a target file
if (source.open("r")) {
   target = new File("c:/data/target.txt")
   target.open("w")

// Copy the source file to the target
   while (!source.eof()) {
      data = source.readln()
      target.writeln(data);
   }
   source.close();
}
   target.close()


getPosition method

Returns the current position of the pointer in an open file.

Syntax

fileObjectName.getPosition()

fileObjectName is the name of a File object.

Description

Use the getPosition method to determine the position of the pointer in a file. See the File object for a description of the pointer. The getPosition method returns the current pointer position; the first byte in a file is byte zero. This method returns -1 if there is an error.


Expressions

An expression is any valid set of literals, variables, operators, and expressions that evaluates to a single value. The value may be a number, a string, or a logical value. Conceptually, there are two types of expressions: those that assign a value to a variable, and those that simply have a value. For example, the expression

x = 7

is an expression that assigns x the value 7. This expression itself evaluates to 7. Such expressions use assignment operators. On the other hand, the expression

3 + 4

simply evaluates to 7; it does not perform an assignment. The operators used in such expressions are referred to simply as operators.

JavaScript has the following kinds of expressions:

•	Arithmetic: evaluates to a number, for example

•	String: evaluates to a character string, for example "Fred" or "234"

•	Logical: evaluates to true or false

The special keyword null denotes a null value. In contrast, variables that have not been assigned a value are undefined, and cannot be used without a run-time error.


Conditional Expressions

A conditional expression can have one of two values based on a condition. The syntax is

(condition) ? val1 : val2

If condition is true, the expression has the value of val1, Otherwise it has the value of val2. You can use a conditional expression anywhere you would use a standard expression. For example,

status = (age >= 18) ? "adult" : "minor"

This statement assigns the value "adult" to the variable status if age is eighteen or greater. Otherwise, it assigns the value "minor" to status.


Assignment Operators
Assignment Operators (=, +=, -=, *=, /=)

An assignment operator assigns a value to its left operand based on the value of its right operand. The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x.

The other operators are shorthand for standard arithmetic operations as follows:

•	x += y means x = x + y

•	x -= y means x = x - y

•	x *= y means x = x * y

•	x /= y means x = x / y

•	x %= y means x = x % y

There are additional assignment operators for bitwise operations:

•	x <<= y means x = x << y

•	x >>= y means x = x >> y

•	x >>>= means x = x >>> y

•	x &= means x = x & y

•	x ^= means x = x ^ y

•	x |= means x = x | y


Operators

JavaScript has arithmetic, string, and logical operators. There are both binary and unary operators. A binary operator requires two operands, one before the operator and one after the operator:

operand1 operator operand2

For example, 3 + 4 or x * y

A unary operator requires a single operand, either before or after the operator:

operator operand

or

operand operator

For example x++ or ++x.


Arithmetic Operators

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

Standard Arithmetic Operators

The standard arthmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). These operators work in the standard way.

Modulus (%)

The modulus operator is used as follows:
var1 % var2

The modulus operator returns the first operand modulo the second operand, that is, var1 modulo var2, in the statement above, where var1 and var2 are variables. The modulo function is the remainder of integrally dividing var1 by var2. For example, 12 % 5 returns 2.

Increment (++)

The increment operator is used as follows:
var++ or ++var

This operator increments (adds one to) its operand and returns a value. If used postfix, with operator after operand (for example x++), then it returns the value before incrementing. If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing.

Decrement (--)

The decrement operator is used as follows:

var-- or --var

This operator decrements (subtracts one from) its operand and returns a value. If used postfix (for example x--) then it returns the value before decrementing. If used prefix (for example, --x), then it returns the value after decrementing.

Unary negation (-)

The unary negation operator must precede its operand. It negates its operand. For example,

x = -x

negates the value of x; that is if x were 3, it would become -3.


Bitwise Operators

Bitwise operators treat their operands as a set of bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number 9 has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

Bitwise Logical Operators

The bitwise logical operators work conceptually as follows:

•	The operands are converted to 32-bit integers, and expressed a series of bits (zeros and ones).

•	Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.

•	The operator is applied to each pair of bits, and the result is constructed bitwise.

The bitwise operators are:

•	Bitwise AND & returns a one if both operands are ones.

•	Bitwise OR | returns a one if either operand is one.

•	Bitwise XOR ^ returns a one if one but not both operands are one.

For example, the binary representation of 9 is 1001, and the binary representation of 15 is 1111. So, when the bitwise operators are applied to these values, the results are as follows:

•	15 & 9 yields 9 (1111 & 1001 = 1001)

•	15 | 9 yields 15 (1111 | 1001 = 1111)

•	15 ^ 9 yields 6 (1111 ^ 1001 = 0110)


Bitwise Shift Operators

The bitwise shift operators are:

•	Left Shift (<<)

•	Sign-propagating Right Shift (>>)

•	Zero-fill Right shift (>>>)

The shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to 32-bit integers, and return a result of the same type as the left operator.

Left Shift (<<)

This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left.

For example, 9>>2 yields 2, because 1001 shifted two bits to the right becomes 10, which is 2. Likewise, -9>>2 yields -3, because the sign is preserved.

Zero-fill right shift (>>>)

This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left.

For example, 19>>>2 yields 4, because 10011 shifted two bits to the right becomes 100, which is 4. For postive numbers, zero-fill right shift and sign-propagating right shift yield the same result.


Logical Operators

Logical operators take logical (Boolean) values as operands. They return a logical value. Logical values are true and false.

And (&&)

Usage: expr1 && expr2

The logical "and" operator returns true if both logical expressions expr1 and expr2 are true. Otherwise, it returns false.

Or (||)

Usage: expr1 || expr2

The logical "or" operator returns true if either logical expression expr1 or expr2 is true. If both expr1 and expr2 are false, then it returns false.

Not (!)

Usage: !expr

The logical "not" operator is a unary operator that negates its operand expression expr. That is, if expr is true, it returns false, and if expr is false, then it returns true.

Short-Circuit Evaluation

As logical expressions are evaluated left to right, they are tested for possible "short circuit" evaluation using the following rule:

•	false && anything is short-circuit evaluated to false.

•	true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations will always be correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.


Comparison Operators
Comparison Operators (= =, >, >=, <, <=, !=)

A comparison operator compares its operands and returns a logical value based on whether the comparison is true or not. The operands may be numerical or string values. When used on string values, the comparisons are based on the standard lexicographical ordering. The operators are:

•	Equal (= =): returns true if the operands are equal.

•	Not equal (!=): returns true if the operands are not equal.

•	Greater than (>): returns true if left operand is greater than right operand. Example: x > y returns true if x is greater than y.

•	Greater than or equal to (>=): returns true if left operand is greater than or equal to right operand. Example: x >= y returns true if x is greater than or equal to y.

•	Less than (<): returns true if left operand is less than right operand. Example: x < y returns true if x is less than y.

•	Less than or equal to (<=): returns true if left operand is less than or equal to right operand. Example: x <= y returns true if x is less than or equal to y.


String Operators

In addition to the comparison operators, which may be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings. For example,

"my " + "string"

returns the string

"my string"

The shorthand assignment operator += can also be used to concatenate strings. For example, if the variable mystring is a string that has the value "alpha", then the expression

mystring += "bet"

evaluates to "alphabet" and assigns this value to mystring.


Operator Precedence

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

The precedence of operators, from lowest to highest is as follows:

comma ,

assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=

conditional ?:

logical-or ||

logical-and &&

bitwise-or |

bitwise-xor ^

bitwise-and &

equality == !=

relational < <= > >=

bitwise shift << >> >>>

addition/subtraction + -

multiply/divide * / %

negation/increment ! ~ - ++ --

call, member () [] .